从后台线程中的另一个类更新GUI

时间:2015-03-09 14:12:41

标签: java multithreading swing event-handling

我来自.NET环境,即使初学者也很容易实现事件监听。但是这次我必须用Java做到这一点。

我的伪代码:

的MainForm -

public class MainForm extends JFrame {
   ...
   CustomClass current = new CustomClass();       
   Thread t = new Thread(current);
   t.start();
   ...
}

CustomClass -

public class CustomClass implements Runnable {

   @Override
   public void run()
   {
      //...be able to fire an event that access MainForm
   }
}

我找到了this example但是我必须在this other one听一个事件。我应该把它们混在一起,我的Java技能水平太低了。 你能帮我详细说明一下吗?

1 个答案:

答案 0 :(得分:1)

我认为您所寻找的是SwingWorker

public class BackgroundThread extends SwingWorker<Integer, String> {

    @Override
    protected Integer doInBackground() throws Exception {
        // background calculation, will run on background thread

        // publish an update
        publish("30% calculated so far");

        // return the result of background task
        return 9;
    }

    @Override
    protected void process(List<String> chunks) { // runs on Event Dispatch Thread
        // if updates are published often, you may get a few of them at once
        // you usually want to display only the latest one:
        System.out.println(chunks.get(chunks.size() - 1));
    }

    @Override
    protected void done() { // runs on Event Dispatch Thread
        try {
            // always call get() in done()
            System.out.println("Answer is: " + get());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

当然,在使用Swing时,您需要更新一些GUI组件而不是打印出来。所有GUI更新都应该在Event Dispatch Thread上完成。

如果您只想进行一些更新且后台任务没有任何结果,您仍应使用get()方法调用done()。如果不这样做,将会吞下doInBackground()中引发的任何异常 - 很难找出应用程序无法正常工作的原因。