Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Why is it important to use invokeLater?

I recently found an example code:

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

The createAndShowGUI() method opens a user interface window. Then I tried to trim the code as the following:

public static void main(String[] args) {
    createAndShowGUI();
}

Both versions work equally well. What is the difference?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

99% of the time either code will work.

However, Swing was designed such that all updates to Swing components should be done on the Event Dispatch Thread (EDT). Read the Swing tutorial on Concurrency for more information.

The problem is the 1% of the time when it might not work. You don't want to waste time trying to debug random problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...