java中如何实现自动计时功能,就是点击一个start按钮就开始计时,以秒为单位
1个回答
展开全部
简单代码如下:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class Timers extends JFrame {
final Label lab = new Label();
Date now = new Date();
@SuppressWarnings("deprecation")
public Timers() {
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
setBounds(550, 270, 200, 150);
final Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date now2 = new Date(now.getTime() + 1000);
now = now2;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
lab.setText(formatter.format(now));
}
});
Button b1 = new Button("开始");
Button b2 = new Button("停止");
b2.setBounds(40, 40, 40, 40);
b1.setBounds(30, 30, 30, 30);
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Button b = (Button) e.getSource();
b.setLabel("开始");
timer.start();
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Button b = (Button) e.getSource();
b.setLabel("停止");
timer.stop();
}
});
this.setLayout(new FlowLayout());
this.add(b2);
this.add(b1);
this.add(lab);
this.setSize(300, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Timers t = new Timers();
t.lab.setText("00:00:00");
}
}
不知是否帮到你,如满意请采纳!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询