2

I will be needing a swing worker for a project that I'm working on, so I attempted to use it. I've tried to use it as shown below, however, this program produces only the "Doing swing stuff" output.

How can I get the SwingWorker to complete the doInBackGround method?

import javax.swing.SwingWorker;

public class WorkerTest {

public static void main(String[] args) {
    Worker a = new Worker();
    a.execute();
    System.out.println("Doing swing stuff");

}

static class Worker extends SwingWorker<Void, Void> {

    protected void done() {
        System.out.println("done");
    }

    @Override
    protected Void doInBackground(){
        try {
            System.out.println("working");
            Thread.sleep(5000);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Oliver-R
  • 163
  • 1
  • 9

1 Answers1

4

Change:

public static void main(String[] args) {
    Worker a = new Worker();
    a.execute();
    System.out.println("Doing swing stuff");
}

To:

public static void main(String[] args) {
    Worker a = new Worker();
    a.execute();
    System.out.println("Doing swing stuff");
    JOptionPane.showConfirmDialog(null, "Cancel", "Cancel this task?", JOptionPane.DEFAULT_OPTION);
}

The option pane (being open) keeps the Event Dispatch Thread alive.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Thanks, that was the problem! – Oliver-R Mar 08 '15 at 17:03
  • I know this is an old thread, but is there a way to accomplish this without having to keep the option pane open? Cheers. – omeanwell Apr 30 '19 at 18:56
  • @omeanwell Sure. Establish a full thread for the `Clip` to work in. Opening an option pane is simply the ***easiest*** way to get it to work. If you wish to pursue this, open a new Q&A - it is too long to go into in comments. – Andrew Thompson Apr 30 '19 at 23:13