javax.swing.Timer vs java.util.Timer inside of a S

2019-01-20 12:50发布

is this better to use javax.swing.Timer inside of a swing application instead of using java.util.Timer?

for example:

Timer timer = new Timer(1000, e -> label.setText(new Date().toString()));
    timer.setCoalesce(true);
    timer.setRepeats(true);
    timer.setInitialDelay(0);
    timer.start();

or

new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            label.setText(new Date().toString());
        }
    }, 0, 1000);

is there any difference between this two?

2条回答
甜甜的少女心
2楼-- · 2019-01-20 13:11

The difference:

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

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

Now. Swing is single threaded.

You must access and mutate Swing components from the EDT only.

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.

Bear one very important thing in mind; if you spend time on the EDT it cannot spend time updating the GUI.

查看更多
仙女界的扛把子
3楼-- · 2019-01-20 13:22

The main difference is that the javax.swing.Timer runs its code on the EDT while the java.util.timer runs on a separate thread. Because of this swing timers are best used if you are manipulating the GUI in any way. Although if you prefer to use a different type of timer then you can still invoke your code on the EDT.

new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            label.setText(new Date().toString());
        }
    });
}, 0, 1000);
查看更多
登录 后发表回答