覆盖SwingWorker中的process()方法

时间:2015-02-04 18:31:52

标签: java multithreading swing user-interface process

我正在尝试使用String动态更新GUI。任何人都可以看到为什么过程方法没有正确覆盖?我已经查看了其他问题,但仍然看不出我是如何正确地覆盖它的。

public class WorkerDemo extends JFrame {

private JLabel counterLabel = new JLabel("Not started");
private Worker worker = new Worker();
private JButton startButton = new JButton(new AbstractAction("Start") {

    @Override
    public void actionPerformed(ActionEvent arg0) {
            worker = new Worker();
            worker.execute();
    }
});
private JButton stopButton = new JButton(new AbstractAction("Stop") {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        worker.cancel(true);
    }
});

public WorkerDemo() {

    add(startButton, BorderLayout.WEST);
    add(counterLabel, BorderLayout.CENTER);
    add(stopButton, BorderLayout.EAST);
    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

class Worker extends SwingWorker<Void, Integer> {

    int counter = 0;
    String abc = "abc";

    @Override
    protected Void doInBackground() throws Exception {
        while(true) {
            abc += abc; 
            publish(abc);
            Thread.sleep(60);
        }
    }

    @Override
    protected void process(List<Object> chunk) {
        // get last result
        String to_return = (String) chunk.get(chunk.size()-1);

        counterLabel.setText(to_return);
    }
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new WorkerDemo();
        }
    });
}
}

1 个答案:

答案 0 :(得分:3)

由于您有SwingWorker<Void, Integer>,因此您已将Integer定义为通过发布和流程方法执行中间结果的类型。这意味着正确的publish()process()方法应该使用Integer

@Override
protected Void doInBackground() throws Exception {
    int someResult = 0;
    ...
    publish(someResult);
    ...
 }


@Override
protected void process(List<Integer> chunk) {
}

有关详细信息,请参阅SwingWorker