Swing is a event driven environment, one of the most important concepts you need to under stand is that you must never, ever, block the Event Dispatching Thread in any way (including, but not limited to, loops, I/O or Thread#sleep
)
Having said that, there are ways to achieve you goal. The simplest is through the javax.swing.Timer
class.
public class TestBlinkingText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BlinkPane());
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected static class BlinkPane extends JLabel {
private JLabel label;
private boolean state;
public BlinkPane() {
label = new JLabel("Hello");
setLayout(new GridBagLayout());
add(label);
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
label.setText("Good-Bye");
repaint();
}
});
timer.setRepeats(false);
timer.setCoalesce(true);
timer.start();
}
}
}
Check out
For more information