Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I wait for a SwingWorker's doInBackground() method?
    text
    copied!<p>Say I have the following code:</p> <pre><code>import java.lang.InterruptedException; import javax.swing.SwingWorker; public class Test { private JDialog window; public Test { // instantiate window } private class Task extends SwingWorker&lt;Void, Void&gt; { public Void doInBackground() { try { Thread.currentThread().sleep(5000); } catch(InterruptedException e) {} return null; } } public void doTask() { Task task = new Task(); task.execute(); } protected void process() { // update various GUI components here } public static void main(String args[]) { Test t = new Test(); t.doTask(); System.out.println("done"); } } </code></pre> <p>I need to wait until <code>t.doTask()</code> is done before printing out 'done', but I'm not sure exactly how. I know I should probably use <code>join()</code> here, but I need a thread to call it on, and I don't know how to get <code>doInBackground()</code>'s thread from where I need to call <code>join()</code>. Thanks for any help.</p> <hr> <p>EDIT: Thanks for the responses. Unfortunately, <code>get()</code> and the like don't quite solve the problem. In my actual code, the SwingWorker also has an overridden <code>process()</code> function that updates a GUI window while the background thread is running. <code>get()</code> does stop 'done' from being printed till after <code>doInBackground</code>, but then the GUI doesn't update. I updated my sample code to reflect this, although now of course it won't compile. </p> <p>Is there a way to get 'done' to print only once <code>doInBackground</code> is finished? Are the GUI update code and the 'done' statement on the same thread? Do I need to make a new thread?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload