Dynamic Clock in java

jt153 picture jt153 · Jun 2, 2010 · Viewed 48.2k times · Source

I want to implement a clock within my program to diusplay the date and time while the program is running. I have looked into the getCurrentTime() method and Timers but none of them seem to do what I would like.

The problem is I can get the current time when the program loads but it never updates. Any suggestions on something to look into would be greatly appreciated!

Answer

jjnguy picture jjnguy · Jun 2, 2010

What you need to do is use Swing's Timer class.

Just have it run every second and update the clock with the current time.

Timer t = new Timer(1000, updateClockAction);
t.start();

This will cause the updateClockAction to fire once a second. It will run on the EDT.

You can make the updateClockAction similar to the following:

ActionListener updateClockAction = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      // Assumes clock is a custom component
      yourClock.setTime(System.currentTimeMillis()); 
      // OR
      // Assumes clock is a JLabel
      yourClock.setText(new Date().toString()); 
    }
}

Because this updates the clock every second, the clock will be off by 999ms in a worse case scenario. To increase this to a worse case error margin of 99ms, you can increase the update frequency:

Timer t = new Timer(100, updateClockAction);