如何更新标签以使其显示新文本?
我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CODe的答案是正确的,但我会选择 SwingWorker 类:
这是解决您问题的正确工具。
CODe's answer is right, but I'd go with the SwingWorker class:
It's the right tool for your problem.