当前位置: 代码迷 >> J2SE >> java秒表小疑点
  详细解决方案

java秒表小疑点

热度:33   发布时间:2016-04-24 01:12:16.0
java秒表小问题
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.Timer;


@SuppressWarnings("serial")
public class Mystopwatch extends JFrame {

 private int minutes=0;
 private int seconds=0;
 private int mseconds=0;
 private Timer timer;
 JTextArea showtime;
 JButton start;
 JButton stop;
 JButton clear;
 Date date;
 
 public Mystopwatch()
 {
 super("秒表");
 start=new JButton("start");
 start.setBackground(Color.GREEN);
 clear=new JButton("clear");
 clear.setBackground(Color.GREEN);
 stop=new JButton("stop");
 stop.setBackground(Color.GREEN);
 showtime=new JTextArea("",1,1);
 showtime.setText("00.00.00");
  Container c = getContentPane();
 c.setLayout(null);
 c.setBackground(Color.YELLOW);
 
 timer=new Timer(10,new MyactionListener2());//以十秒为一个进制
 this.pack();
 
 showtime.setBounds(new Rectangle(40,20,100,20));
 start.setBounds(new Rectangle(20,60,70,20));
 stop.setBounds(new Rectangle(90,60,70,20));
 clear.setBounds(new Rectangle(40,90,90,20));
 c.add(showtime);
 c.add(start);
 c.add(stop);
 c.add(clear);
 start.addActionListener(new Myactionlistener1());
 stop.addActionListener(new Myactionlistener1());
 clear.addActionListener(new Myactionlistener1());
 
 }
 private class MyactionListener2 implements ActionListener
 {
  public void actionPerformed(ActionEvent e)
  {
  String min,sec,msec,time;
  mseconds++;
  if(mseconds==100)
  {
  mseconds=0;
  seconds++;
  }
  if(seconds==60)
  {
  seconds=0;
  minutes++;
  }
  if(minutes==60)
  {
  minutes=0;
  }
  if(minutes<10)
  min="0"+minutes+":";
  else
  min=minutes+":";
  if(seconds<10)
  sec="0"+seconds+":";
  else
  sec=seconds+":";
  if(mseconds<10)
  msec="0"+mseconds;
  else 
  msec=mseconds+"";
  time=min+sec+msec;
  showtime.setText(time);
  }
 }
private class Myactionlistener1 implements ActionListener
{
 public void actionPerformed(ActionEvent e)
 {
  if(e.getSource()==start)
  {
  timer.start();
  }
  if(e.getSource()==stop)
  {
  timer.stop();
  }
  if(e.getSource()==clear)
  {
  showtime.setText("00.00.00");
  timer.stop();
  }
 }
 }
 public static void main(String rags[])
 {
  Mystopwatch stopwatch=new Mystopwatch();
  stopwatch.setSize(200, 200);
  stopwatch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  stopwatch.setVisible(true);
 }

}

新手一个,做 了一个秒表,但时间总是有点延误,不会改。希望哪位高手帮我修改一下,最好使用date类,使他和系统时间一致



------解决方案--------------------
java里面有格式化date格式的,可以定位到秒!Spd
  相关解决方案