Oliver-R
Oliver-R

Reputation: 173

SwingWorker not executing doInBackGround()

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;
    }
}
}

Upvotes: 2

Views: 1604

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

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.

Upvotes: 5

Related Questions