使用 Swingworker 不断更新 GUI [英] Using Swingworker to constantly update a GUI
问题描述
在我的代码中,用户按下一个按钮,然后我希望它调用一个 SwingWorker 后台线程,在那里我基本上遍历一个列表,将它与其他数据交叉引用,然后使用 JLabel 为每个更新 GUI通过我的循环.问题是我知道我应该在 doInBackground() 中执行此操作,但是我没有什么可返回的,而且我还想在每次循环循环时使用新的 JLabel 更新 JPanel.我该怎么做呢?谢谢!
In my code, the user presses a button, and then I want this to invoke a SwingWorker background thread, where I basically loop through a list, cross reference it with other data, and then update the GUI with a JLabel for every pass through my loop. The problem is I know I should do this in doInBackground(), but I have nothing to return, and I also want to update the JPanel with a new JLabel every time my loop loops. How do I do this? Thanks!
推荐答案
这是一个我非常喜欢的完整示例 Swing Worker例子
Here is a complete example i really like Swing Worker Example
你必须使用 publish()
并覆盖 process()
You have to use publish()
and override process()
示例:
class Worker extends SwingWorker<Void, String> {
@Override
protected void doInBackground() throws Exception {
//here you make heavy task this is running in another thread not in EDT
//process after some time call publish()
}
@Override
protected void process(List<String> chunks) {
//this is executed in the EDT
//here you update your label
}
}
这篇关于使用 Swingworker 不断更新 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!