Updating the state of a Swing component must happen on the Event Dispatch Thread (the EDT). The javax.swing.Timer
triggers its ActionListener
on the EDT, making it a good choice to perform Swing operations.
The following example updates the text of a JLabel
each two seconds:
//Use a timer to update the label at a fixed interval
int delay = 2000;
Timer timer = new Timer( delay, e -> {
String revertedText = new StringBuilder( label.getText() ).reverse().toString();
label.setText( revertedText );
} );
timer.start();
A complete runnable example which uses this Timer
is given below: the UI contains a label, and the text of the label will be reverted each two seconds.
import javax.swing.*;
import java.awt.*;
public final class RepeatTaskFixedIntervalExample {
public static void main( String[] args ) {
EventQueue.invokeLater( () -> showUI() );
}
private static void showUI(){
JFrame frame = new JFrame( "Repeated task example" );
JLabel label = new JLabel( "Hello world" );
//Use a timer to update the label at a fixed interval
int delay = 2000;
Timer timer = new Timer( delay, e -> {
String revertedText = new StringBuilder( label.getText() ).reverse().toString();
label.setText( revertedText );
} );
timer.start();
frame.add( label, BorderLayout.CENTER );
frame.pack();
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
frame.setVisible( true );
}
}