SwingWorker没有执行doInBackGround()

时间:2015-03-08 16:43:56

标签: java swing swingworker

我将需要一个摇摆工作者来完成我正在进行的项目,所以我试图使用它。我试图使用它,如下所示,但是,这个程序只产生“做摇摆的东西”输出。

如何让SwingWorker完成doInBackGround方法?

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 个答案:

答案 0 :(得分:4)

变化:

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

要:

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

选项窗格(正在打开)使事件调度线程保持活动状态。