My stopwatch is giving me a weird time.
It shows as 16:00:00:000, it also is putting the seconds into the millisecond slot. I think the problem is the date formatter somehow. Without the dateformater adn just using a decimalformater it comes out correctly. I just need it to show hours, minutes and seconds.
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();
}
});
}
}
DateFormatformats an instant in time specified by the millisecond value and you are attempting to use it to format an interval. Nothing in the JDK covers your use case, but JodaTime does. You should use JodaTime, anyway.