如何让JLabel文字显示1秒?

发布于 2024-12-06 17:04:03 字数 445 浏览 0 评论 0原文

我希望我的错误消息暂时显示在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听风念你 2024-12-13 17:04:03

我假设您在事件分派线程上调用此方法。 (如果没有,您应该这样做,因为几乎所有 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文