使用Swingworker不断更新GUI

use*_*980 0 java user-interface swing jlabel swingworker

在我的代码中,用户按下一个按钮,然后我希望它调用一个SwingWorker后台线程,我基本上遍历一个列表,与其他数据交叉引用它,然后用JLabel更新GUI,每次通过我的环.问题是我知道我应该在doInBackground()中执行此操作,但是我没有什么可以返回的,并且我还希望每次循环时都使用新的JLabel更新JPanel.我该怎么做呢?谢谢!

nac*_*okk 6

这是一个完整的例子,我非常喜欢Swing Worker Example

你必须使用publish()和覆盖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
    }
}
Run Code Online (Sandbox Code Playgroud)