用Java编写的计时器,有三按钮。开始,停止,复位。问题出在:按下复位后再按开始,还是从按下停止的时间开始计时。请问下应该怎么改写代码,使得按下开始就是从0计时。代码如下:
import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.PopupMenu; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.Timer; public class TimeCount extends JFrame { JLabel lbl = new JLabel(); Date now = new Date(); public TimeCount() { now.setHours(0); now.setMinutes(0); now.setSeconds(0); 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"); lbl.setText(formatter.format(now)); } }); Button b1 = new Button("开始计时"); Button b2 = new Button("停止计时"); Button b3 = new Button("复位"); b1.setSize(100, 50); b2.setSize(100, 50); b3.setSize(100, 50); 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(); } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { lbl.setText("00:00:00"); } }); this.setLayout(new FlowLayout()); //this.add(txt); this.add(b1); this.add(b2); this.add(b3); this.add(lbl); this.setSize(300, 200); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { TimeCount t = new TimeCount(); } }
管理員
努力提升
Mr_atom
相关分类