我的秒表给了我一个奇怪的时间。它显示为 16:00:00:000,它还将秒数放入毫秒槽中。我认为问题出在日期格式化程序上。如果没有 dateformater 和仅使用 decimalformater,它就会正确显示。我只需要它显示小时、分钟和秒。
public class StopWatchTest extends JLabel implements ActionListener {
private static final String Start = "Start";
private static final String Stop = "Stop";
private SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
private Timer timer = new javax.swing.Timer(100, this);
private long now = System.currentTimeMillis();
public StopWatchTest() {
this.setHorizontalAlignment(JLabel.CENTER);
this.setText(when());
}
public void actionPerformed(ActionEvent ae) {
setText(when());
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
private String when() {
return df.format((System.currentTimeMillis() - now) / 1000d);
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final StopWatchTest jtl = new StopWatchTest();
jtl.setFont(new Font("Dialog", Font.BOLD, 32));
f.add(jtl, BorderLayout.CENTER);
final JButton button = new JButton(Stop);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (Stop.equals(cmd)) {
jtl.stop();
button.setText(Start);
} else {
jtl.start();
button.setText(Stop);
}
}
});
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
jtl.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
create();
}
});
}
}