SwingUtilities.invokeLater和SwingWorker之间的区别< Void,Object>? [英] Difference between SwingUtilities.invokeLater and SwingWorker<Void, Object>?

查看:223
本文介绍了SwingUtilities.invokeLater和SwingWorker之间的区别< Void,Object>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

  //有些代码需要一些时间来处理
( new SomeJFrame())。setVisible(true);

SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
(new SomeJWindow())。start(); //开始新线程
}
});

并且:

  class doGraphics扩展了SwingWorker< Void,Object> {

@Override
public Void doInBackground(){

//一些代码,需要一些时间来处理
(新的SomeJFrame() ).setVisible(真);

返回null;
}

@Override
protected void done(){

(new SomeJWindow())。start(); //开始一个新线程

}
}
(new doGraphics())。execute();

哪种方法更好用?

解决方案

SwingUtilities.invokeLater
接受Runnable并稍后在ui线程中调用它。通常用于短期运行ui相关工作。



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



<但是,SwingWorker的 doInBackground()方法也可以通过调用 publish()方法发布中间结果。 SwingWorker 将确保发布的结果由Event Dispatch Thread处理。您可以通过实现 process()方法来挂钩。


What is the difference between:

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

And:

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

Which method is better to use?

解决方案

SwingUtilities.invokeLater takes a Runnable and invokoes it in the ui thread later. Usually for short running ui related work.

SwingWorker runs the main work in a non ui thread - the worker thread. After the long running work is done the done() method is invoked in the ui thread (Event Dispatch Thread).

But the SwingWorker's doInBackground() method can also publish intermediate results by invoking the publish() method. The SwingWorker will than ensure that the results to publish are processed by the Event Dispatch Thread. You can hook in by implementing the process() method.

这篇关于SwingUtilities.invokeLater和SwingWorker之间的区别&lt; Void,Object&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆