请点击上面的“开始计时”按钮来启动计时器。输入框会一直进行计时,从 0 开始。点击“停止计时”按钮可以终止计时。
BS还是CS结构,用线程,或者用setTimer
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Time extends JFrame implements ActionListener {
private JButton start, end, resert;
private Timer t;
private long d1, d2;
private JLabel time;
public Time() {
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setBounds(0, 0, 300, 200);
this.setLayout(null);
this.setResizable(false);
start = new JButton("开始");
end = new JButton("停止");
resert = new JButton("重置");
time = new JLabel();
time.setBounds(110, 0, 80, 130);
start.setBounds(20, 130, 60, 30);
end.setBounds(120, 130, 60, 30);
resert.setBounds(220, 130, 60, 30);
add(time);
add(start);
add(end);
add(resert);
start.addActionListener(this);
end.addActionListener(this);
resert.addActionListener(this);
this.setVisible(true);
}
public static void main(String[] arg) {
new Time();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object obj = e.getSource();
if (obj.equals(start)) {
d1 = new Date().getTime();
t = new Timer();
t.schedule(new MyTask(), 0, 1);
}
if (obj.equals(resert)) {
time.setText("00:00:00:00");
}
if (obj.equals(end)) {
t.cancel();
}
}
public String convert(long ctime) {
long h = ctime / 3600000;
long m = (ctime % 3600000) / 60000;
long s = (ctime % 60000) / 1000;
long n = (ctime % 1000) / 10;
String hh = h < 10 ? "0" : "";
String mm = m < 10 ? "0" : "";
String ss = s < 10 ? "0" : "";
String nn = n < 10 ? "0" : "";
String strTime = hh + h + ":" + mm + m + ":" + ss + s + ":" + nn + n;
return strTime;
}
private class MyTask extends TimerTask {
@Override
public void run() {
d2 = new Date().getTime();
long t = d2 - d1;
String str = convert(t);
time.setText(str);
}
}
}