[英]Java timer, update every second
我想从系统中获取当前日期和时间,我可以使用以下代码进行操作:
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));
}
这样做很好,因为它可以毫无问题地获取当前日期和时间,但是它不是动态的,因为除非再次按下该按钮,否则时间不会更新。 所以我想知道如何通过每秒更新一次功能以刷新时间来使此按钮更具动态性。
您可以使用执行程序定期进行更新。 像这样:
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);
首先定义一个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));
}
});
}
}
然后,您需要在启动应用程序或UI时创建一个java.util.Timer。 例如,您的main()方法。
...
Timer timer = new Timer();
timer.schedule(new MyTimerTask(label), 0, 1000);
...
Swing计时器(javax.swing.Timer的一个实例)在指定的延迟后触发一个或多个动作事件。 请参阅: http : //docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
这个答案可能对您有用
为此使用Swing计时器:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.