SwingWorker not executing doInBackGround()

和自甴很熟 提交于 2019-12-11 03:17:52

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/28929059/swingworker-not-executing-doinbackground

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