开发者

How to display JLabel text for 1 second?

开发者 https://www.devze.com 2023-04-09 01:24 出处:网络
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

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;
   开发者_如何学JAVA while(ctr<2){
        try {
            lblError.setText(msg);
            lblError.repaint();
            Thread.sleep(500);
        } catch (Exception e) {}
        ctr++;
    }
    lblError.setText("");
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号