本文介绍了SwingWorker 不执行 doInBackGround()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事的项目需要一个摇摆工人,所以我尝试使用它.我尝试使用它,如下所示,但是,该程序仅产生Doing swing stuff"输出.

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.

如何让 SwingWorker 完成 doInBackGround 方法?

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

推荐答案

更改:

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

选项窗格(处于打开状态)使事件调度线程保持活动状态.

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

这篇关于SwingWorker 不执行 doInBackGround()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 22:45