2

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.

Niral Mehta
  • 63
  • 1
  • 2
  • 11
  • http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html – JB Nizet Nov 02 '14 at 12:46
  • @JBNizet `Timer` has actually a "flaw" in most of its implementations (see [here](http://stackoverflow.com/a/17588398/1093528)) – fge Nov 02 '14 at 12:58
  • 1
    @fge: this question is about java.util.Timer, not javax.swing.Timer. In my implementation of javax.swing.Timer, nanoTime is used. – JB Nizet Nov 02 '14 at 13:05

4 Answers4

4

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

ScheduledExecutorService e= Executors.newSingleThreadScheduledExecutor();
e.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    // do stuff
    SwingUtilities.invokeLater(new Runnable() {
       // of course, you could improve this by moving dateformat variable elsewhere
       DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
       Date date = new Date();
       CurrentDateTime.setText(dateandtime.format(date));
    });
  }
}, 0, 1, TimeUnit.SECONDS);
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • Thank you for your help! this works perfectly; however just to help any one else, an **@Override** should be invoked so that the code can run well :) – Niral Mehta Nov 02 '14 at 14:43
1

Use Swing Timer for this :

DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Timer t = new Timer(500, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Date date = new Date();
        CurrentDateTime.setText(dateandtime.format(date));
        repaint();
    }
});
t.start();
afzalex
  • 8,598
  • 2
  • 34
  • 61
1

First define a TimerTask

class MyTimerTask extends TimerTask  {
    JLabel currentDateTime;

     public MyTimerTask(JLabel aLabel) {
         this.currentDateTime = aLabel;
     }

     @Override
     public void run() {
         SwingUtilities.invokeLater(
                 new Runnable() {

                    public void run() {
                        // You can do anything you want with 'aLabel'
                         DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                         Date date = new Date();
                         currentDateTime.setText(dateandtime.format(date));

                    }
                });
     }
}

Then, you need to create a java.util.Timer in startup of your application or UI. For example your main() method.

...

Timer timer = new Timer();
timer.schedule(new MyTimerTask(label), 0, 1000);

...
MK Aftab
  • 39
  • 7
  • 2
    This is incorrectly synchronized; it accesses the `JLabel` from the timer's thread. – trashgod Nov 02 '14 at 13:37
  • 1
    @MKAftab The comment by trashgod is correct; this example code is dangerously incorrect. Manipulating Swing components on a background thread will cause strange behavior and likely fail. Learn [how to handle concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) properly. Either revamp this code or withdraw the answer. – Basil Bourque Nov 03 '14 at 00:59
  • 2
    @Basil Your are correct. I edited my answer. Now every things goes through EDT. But now, I thinks, using Swing-Timer is a more convenient solution. – MK Aftab Nov 03 '14 at 16:43
  • Looks good. Now replace the use of java.util.Date and SimpleDateFormat with [Joda-Time](http://www.joda.org/joda-time/) and it would be perfect. ;-) – Basil Bourque Nov 03 '14 at 20:53
0

A Swing timer (an instance of javax.swing.Timer) fires one or more action events after a specified delay. Refer: http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
This answer might be useful for you

Community
  • 1
  • 1
Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51