我正在 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 调用工作得很好。基本上我想知道我应该做什么来使标签显示它已设置的新文本。
最佳答案
CODe 的答案是正确的,但我会选择 SwingWorker类:
An abstract class to perform lengthy GUI-interacting tasks in a dedicated thread.
这是解决您问题的正确工具。
关于java - 如何更新标签以使其显示新文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358723/