How do I wait for a SwingWorker's doInBackground() method?

柔情痞子 提交于 2019-11-28 10:56:26
ColinD

Typically anything that needs to be done after a SwingWorker completes its background work is done by overriding the done() method in it. This method is called on the Swing event thread after completion, allowing you to update the GUI or print something out or whatever. If you really do need to block until it completes, you can call get().

NB. Calling get() within the done() method will return with your result immediately, so you don't have to worry about that blocking any UI work.

Calling get() will cause the SwingWorker to block.

From the Javadocs:

T get() 
      Waits if necessary for the computation to complete, 
      and then retrieves its result.

Your code will then look like:

public static void main(String args[])
{
    Test t = new Test();
    t.doTask();
    t.get();  // Will block
    System.out.println("done");
}

You can override the done() method, which is called when the doInBackground() is complete. The done() method is called on EDT. So something like:

@Override
protected void done() {
  try {
    super.get();

    System.out.println("done");
    //can call other gui update code here
  } catch (Throwable t) {
    //do something with the exception
  }
}

Calling the get() method inside the done helps get back any exceptions that were thrown during the doInBackground, so I highly recommend it. SwingWorker uses Callable and Future internally to manage the background thread, which you might want to read up on instead of trying the join/yield approach.

In general, you must hold onto the SwingWorker until it finishes, which you can test by calling isDone() on it. Otherwise just call get() which makes it wait.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!