-1

I have a JLabel which I want to change momentarily, here is the code I have written to do so:

infoLabel.setText("Added");
try {
   TimeUnit.MILLISECONDS.sleep(300);
}
catch(InterruptedException ex)
{
}

infoLabel.setText("Action"); //funny part is when I comment this line it works

My default text for the label is 'Action'

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Snedden27
  • 1,870
  • 7
  • 32
  • 60

4 Answers4

3

Swing is a single threaded frame work, that means, if you do anything that stops this thread, then it can't respond to any new events, including paint requests.

Basically, TimeUnit.MILLISECONDS.sleep(300) is causing the Event Dispatching Thread to be put to sleep, preventing it from processing any new paint requests (amongst other things).

Instead, you should use a javax.swing.Timer

Take a look at

For more details

For example...

infoLabel.setText("Added");

Timer timer = new Timer(300, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        infoLabel.setText("Action");
    }
});
timer.setRepeats(false);
timer.start();

Note, 300 milliseconds is a really short time, you might like to start with a value a little larger like 2000, which is 2 seconds ;)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You're sleeping the Swing event thread putting the entire GUI to sleep. Don't do that. Use a Swing Timer instead.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Your application is run on a single thread, so when you sleep the thread, you prevent it from making any GUI updates.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
0

Are you sure you are doing things properly? By doing everything (including sleep) in the GUI thread, it will always be busy and never get back to Java in order to let the GUI be redrawn.

Search for EDT (Event dispatch thread) for more info. Here is one question on the subject: Processing code doesn't work (Threads, draw(), noLoop(), and loop())

Community
  • 1
  • 1
John3136
  • 28,809
  • 4
  • 51
  • 69