gpt4 book ai didi

Java定时器,每秒更新一次

转载 作者:行者123 更新时间:2023-11-29 03:15:52 26 4
gpt4 key购买 nike

我想从系统中获取当前日期和时间,我可以使用以下代码:

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

这样做很好,因为它会获取当前日期和时间,没问题,但它不是动态的,因为除非再次按下按钮,否则时间不会更新。所以我想知道如何通过每秒更新函数来刷新时间来使这个按钮更加动态。

最佳答案

您可以使用 executor定期更新。像这样:

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

关于Java定时器,每秒更新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com