Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Clock in java

Tags:

java

swing

clock

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!

like image 233
jt153 Avatar asked Jun 02 '10 16:06

jt153


2 Answers

This sounds like you might have a conceptual problem. When you create a new java.util.Date object, it will be initialised to the current time. If you want to implement a clock, you could create a GUI component which constantly creates a new Date object and updates the display with the latest value.

One question you might have is how to repeatedly do something on a schedule? You could have an infinite loop that creates a new Date object then calls Thread.sleep(1000) so that it gets the latest time every second. A more elegant way to do this is to use a TimerTask. Typically, you do something like:

private class MyTimedTask extends TimerTask {

   @Override
   public void run() {
      Date currentDate = new Date();
      // Do something with currentDate such as write to a label
   }
}

Then, to invoke it, you would do something like:

Timer myTimer = new Timer();
myTimer.schedule(new MyTimedTask (), 0, 1000);  // Start immediately, repeat every 1000ms
like image 74
PhilDin Avatar answered Oct 11 '22 02:10

PhilDin


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);
like image 44
jjnguy Avatar answered Oct 11 '22 01:10

jjnguy