我想抓住从系统中,我可以用这个代码做的当前日期和时间:
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));
}
这样做是罚款,它会抢他当前日期时间NAD没有问题,但它不是动态的时间,除非再次按下按钮将不会更新。 所以我想知道我怎么能让通过更新功能,每秒刷新一次该按钮更有活力。
您可以使用执行定期更新。 事情是这样的:
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));
}
});
}
}
然后,你需要在你的应用程序或用户界面的启动创建java.util.Timer中。 例如您的main()方法。
...
Timer timer = new Timer();
timer.schedule(new MyTimerTask(label), 0, 1000);
...
摆动计时器(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();