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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With