SwingUtilities.invokeLater和SwingWorker<Void, Object>之间有什么区别?

5

以下两者有什么不同:

    //Some code, takes a bit of time to process
    (new SomeJFrame()).setVisible(true);

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            (new SomeJWindow()).start();//Start a new thread
        }
    });

并且:

    class doGraphics extends SwingWorker<Void, Object> {

        @Override
        public Void doInBackground() {

           //Some code, takes a bit of time to process
            (new SomeJFrame()).setVisible(true);

            return null;
        }

        @Override
        protected void done() {

            (new SomeJWindow()).start();//Start a new thread

        }
    }
    (new doGraphics()).execute();

哪种方法更好使用?

1个回答

17

SwingUtilities.invokeLater接受一个Runnable对象,稍后在UI线程中调用它。通常用于与ui相关的短时间运行的工作。

SwingWorker在非UI线程 - 工作线程中运行主要工作。完成长时间运行的工作后,done()方法将在UI线程(事件分派线程)中调用。

但是,SwingWorkerdoInBackground() 方法也可以通过调用 publish() 方法发布中间结果。然后 ,SwingWorker 将确保由事件分派线程处理要发布的结果。您可以通过实现 process() 方法来连接它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接