Swing 应用程序中的 javax.swing.Timer 与 java.util.Timer [英] javax.swing.Timer vs java.util.Timer inside of a Swing application
问题描述
在 Swing 应用程序中使用 javax.swing.Timer
比使用 java.util.Timer
更好吗?
is this better to use javax.swing.Timer
inside of a swing application instead of using java.util.Timer
?
例如:
Timer timer = new Timer(1000, e -> label.setText(new Date().toString()));
timer.setCoalesce(true);
timer.setRepeats(true);
timer.setInitialDelay(0);
timer.start();
或
new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
label.setText(new Date().toString());
}
}, 0, 1000);
这两者有什么区别吗?
推荐答案
区别:
一个 java.util.Timer
启动它自己的 Thread
来运行任务.
A java.util.Timer
starts its own Thread
to run the task on.
javax.swing.Timer
调度任务以在 美国东部时间.
现在.Swing 是单线程的.
您必须仅从 EDT 访问和改变 Swing 组件.
You must access and mutate Swing components from the EDT only.
因此,要每 X 秒更改一次 GUI,请使用 Swing 计时器.要执行后台业务逻辑,请使用其他计时器.或者更好的 ScheduledExecutorService
.
Therefore, to make changes to the GUI every X seconds, use the Swing timer. To do background business logic use the other timer. Or better a ScheduledExecutorService
.
记住一件非常重要的事情;如果你花时间在 EDT 上,它就不会花时间更新 GUI.
Bear one very important thing in mind; if you spend time on the EDT it cannot spend time updating the GUI.
这篇关于Swing 应用程序中的 javax.swing.Timer 与 java.util.Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!