3

I am wanting my error messages to display in a JLabel temporarily, then set the text back to "". But instead it looks like it just skips over setting the message. I've stepped through the code and found it's setting the text, but it isn't displaying for some reason. I've even tried the repaint() method, but still nothing. Any help would be greatly appreciated.

Here's what I have:

public void displayError(String msg){
    int ctr = 0;
    while(ctr<2){
        try {
            lblError.setText(msg);
            lblError.repaint();
            Thread.sleep(500);
        } catch (Exception e) {}
        ctr++;
    }
    lblError.setText("");
}
MByD
  • 135,866
  • 28
  • 264
  • 277
user967870
  • 31
  • 3
  • I don't actually remember enough about swing to help you with the label part, but I just I should point out that you should never assume that the number of milliseconds you've specified in Thread.sleep have actually occurred when you leave the try block. Especially since you're just swallowing the Exception. I'm also not sure why you'd specifically want to set the text to the same value twice. – Vala Sep 27 '11 at 20:55
  • 3
    See [How to Use Swing Timers](http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html). – trashgod Sep 27 '11 at 20:55
  • I took out my Exception handling just to show what I wanted to do. The while loop was just for testing purposes. I wanted to change it both before and after the Thread.sleep(). As far as testing the number of milliseconds for that method, keep in mind this is an extremely small app for me and my brother. If something like that goes wrong it wouldn't be very detrimental. Although, having made a game and animation, I can definitely see your point. Thanks for the input. – user967870 Sep 27 '11 at 22:40
  • That Swing Timers link was a huge help. Thanks, trashgod. – user967870 Sep 27 '11 at 22:44

1 Answers1

8

I'm assuming that you're calling this method on the event dispatch thread. (If not, you should be, since almost all Swing calls should be made there.)

You need to allow the thread to retake control, which it's not able to do because of your Thread.sleep(). Look instead at invoking a Timer or SwingWorker background thread which, after two seconds, will reset the text.

http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49