为什么使用invokeLater很重要? [英] Why is it important to use invokeLater?

查看:113
本文介绍了为什么使用invokeLater很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了一个示例代码:

I recently found an example code:

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

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?

推荐答案

99%的时间代码都能正常工作。

99% of the time either code will work.

但是,Swing的设计使得Swing组件的所有更新都应该在Event Dispatch Thread(EDT)上完成。有关详细信息,请阅读并发上的Swing教程。

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.

问题是1%的时间可能无效。您不想浪费时间尝试调试随机问题。

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.

这篇关于为什么使用invokeLater很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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