如何更新标签以使其显示新文本?

发布于 2024-09-11 12:12:53 字数 748 浏览 9 评论 0原文

我正在 netbeans 中制作一个应用程序,并希望有一个状态标签来告诉程序在任何给定时刻发生的情况。有大量代码,但它的作用大致如下:假设 statusLabel 是一个已经放入程序中的标签,并且每个函数都是一个昂贵的函数,需要几秒钟的时间。

statusLabel.setText("Completing Task 1");
System.out.println("Completing Task 1");
this.getFrame().repaint(); //I call this function and the two functions below it but the label still does not change.
statusLabel.updateUI(); //Doesn't seem to do much.
statusLabel.revalidate(); //Doesn't seem to do much.
this.completeTask1();
statusLabel.setText("Completing Task 2");
System.out.println("Completing Task 2");
statusLabel.revalidate();
this.getFrame().repaint();
...

这会一直持续到 UI 完成 4 个任务为止。在整个过程中,直到每个任务完成后,标签才会更新,然后显示“正在完成任务 4”。但 System.out.println 调用工作得很好。基本上我想知道我应该做什么来使标签显示它已设置的新文本。

I am making an application in netbeans and want to have a status label that tells what is going on in the program at any given moment. There is a ton of code, but here is pretty much what it does: Just pretend that statusLabel is a label that has already been put in the program and each of the functions is an expensive function that takes a few seconds.

statusLabel.setText("Completing Task 1");
System.out.println("Completing Task 1");
this.getFrame().repaint(); //I call this function and the two functions below it but the label still does not change.
statusLabel.updateUI(); //Doesn't seem to do much.
statusLabel.revalidate(); //Doesn't seem to do much.
this.completeTask1();
statusLabel.setText("Completing Task 2");
System.out.println("Completing Task 2");
statusLabel.revalidate();
this.getFrame().repaint();
...

This goes on until the UI has completed 4 tasks. During the entire process the label does not update until after every single task has been completed, and then it says "Completing Task 4". The System.out.println calls work perfectly though. Basically I am wondering what I should do to make the label show the new text that it has been set to.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

贱贱哒 2024-09-18 12:12:53

CODe的答案是正确的,但我会选择 SwingWorker 类:

一个抽象类,用于在专用线程中执行冗长的 GUI 交互任务。

这是解决您问题的正确工具。

CODe's answer is right, but I'd go with the SwingWorker class:

An abstract class to perform lengthy GUI-interacting tasks in a dedicated thread.

It's the right tool for your problem.

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