Java timer, update every second

2019-07-25 22:57发布

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.

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-25 23:42

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

查看更多
姐就是有狂的资本
3楼-- · 2019-07-25 23:48

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);
查看更多
贼婆χ
4楼-- · 2019-07-25 23:50

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();
查看更多
姐就是有狂的资本
5楼-- · 2019-07-25 23:58

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);

...
查看更多
登录 后发表回答