In my program I'm trying to make a JLabel
update after a few seconds by using Thread.sleep(3000)
in between the label.setText()
calls.
public void actionPerformed(ActionEvent e)
{
gameUpdate.label.setText("text a");
try {
Thread.sleep(3000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
gameUpdate.label.setText("text b");
}
What happens is the button is pressed and the label doesn't update. Then after 3 seconds the label is updated to "text b". I can't understand why this would be happening.
I can't understand why this would be happening.
Your are invoking the code from the ActionListener and this code executes on the Event Dispatch Thread (EDT).
The Thread.sleep(...) causes the EDT to sleep which means the GUI can't repaint itself until it is finished sleeping.
You need to use a separate Thread. Check out the section from the Swing tutorial on Concurrency for more information. You can use a SwingWorker
to publish
results as they become available.
Or, the other option is to use a Swing Timer
to schedule the updating of the text. The tutorial also has a section on How to Use Timers.