Home > DeveloperSection > Forums > How to update Java timer every second?
Allen Scott

Total Post:41

Points:289
Posted on    November-04-2014 10:46 PM

 Java Swing  Date  Time  Timer 
Ratings:


 1 Reply(s)
 668  View(s)
Rate this:
I want to grab the current date and time from the system which i can do with this code:

private void GetCurrentDateTimeActionPerformed(java.awt.event.ActionEvent evt)

{                                                  

     DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

     Date date = new Date();

     CurrentDateTime.setText(dateandtime.format(date));

}


Doing this is fine as it will grab he current date nad time no problem, however it is not dynamic as the time will not update unless the button is pressed again. So I was wondering how I could make this button more dynamic by updating the function every second to refresh the time.



Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    November-04-2014 11:47 PM

You can use an executor to update that periodically. Something like this:

ScheduledExecutorService e= Executors.newSingleThreadScheduledExecutor();
e.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    SwingUtilities.invokeLater(new Runnable() {
       DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
       Date date = new Date();
       CurrentDateTime.setText(dateandtime.format(date));
    });
  }
}, 0, 1, TimeUnit.SECONDS);

Don't want to miss updates? Please click the below button!

Follow MindStick