Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

java - Difference between SwingUtilities.invokeLater and SwingWorker<Void, Object>?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...