如何让JLabel文字显示1秒?
我希望我的错误消息暂时显示在 JLabel 中,然后将文本设置回“”。但相反,它看起来只是跳过了设置消息。我已经浏览了代码,发现它正在设置文本,但由于某种原因它没有显示。我什至尝试过 repaint() 方法,但仍然没有任何效果。任何帮助将不胜感激。
这是我所拥有的:
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("");
}
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("");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您在事件分派线程上调用此方法。 (如果没有,您应该这样做,因为几乎所有 Swing 调用都应该在那里进行。)
您需要允许线程重新获得控制权,但由于您的 Thread.sleep(),它无法做到这一点。相反,请考虑调用 Timer 或 SwingWorker 后台线程,两秒后,它将重置文本。
http://download.oracle.com/javase/tutorial/uiswing/concurrency /dispatch.html
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