Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.swing.Timer vs java.util.Timer inside of a Swing application

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?

like image 733
FaNaJ Avatar asked Jul 29 '14 22:07

FaNaJ


2 Answers

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.

like image 199
Boris the Spider Avatar answered Oct 27 '22 20:10

Boris the Spider


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);
like image 43
BitNinja Avatar answered Oct 27 '22 20:10

BitNinja