使用Swingworker不断更新GUI

时间:2013-08-26 17:51:09

标签: java swing user-interface jlabel swingworker

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

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:4)

阅读使用Swing Worker的Swing教程,尤其是Tasks that Have Interim Results上的部分。

您需要根据循环中的要求调用publish()方法。