在Swing应用程序内部的javax.swing.Timer与java.util.Timer [英] javax.swing.Timer vs java.util.Timer inside of a Swing application

查看:190
本文介绍了在Swing应用程序内部的javax.swing.Timer与java.util.Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好在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);

这两者有什么区别吗?

推荐答案

区别:

A java.util.Timer 启动它自己的线程来运行任务。

A java.util.Timer starts its own Thread to run the task on.

A javax.swing.Timer EDT 上安排执行任务。

A javax.swing.Timer schedules tasks for execution on the EDT.

现在。 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆