Java SwingWorker在main方法中不起作用?

时间:2016-07-13 07:27:10

标签: java swing swingworker

我只是尝试使用代码,但是swingworker没有执行。如果我把它放在GUI应用程序的一个动作中(在按钮点击事件中)它正在执行。这是什么技术原因?

public static void main(String[] args) {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}

2 个答案:

答案 0 :(得分:2)

有关详细信息,请参阅Concurrency in Swing: Initial Threads

添加SwingUtilities.invokeAndWait

后可以使用
public static void main(String[] args) {

        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    new SwingWorker<Object, Object>() {
                        @Override
                        protected Object doInBackground() throws Exception {
                            System.out.println("do in background.....");
                            return null;
                        }
                    }.execute();

                }
            });
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

答案 1 :(得分:0)

这是一个时间问题。如果后台任务在main方法之前完成,它将打印“do in background ......”:

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

    Thread.sleep(100L);
}

如果主要在后台任务有机会运行之前完成,它将不会打印任何内容:

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            Thread.sleep(100L);
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}