为什么在main方法中使用SwingUtilities.invokeLater? [英] Why to use SwingUtilities.invokeLater in main method?

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

问题描述

经过多年的Java编程,我总是习惯于创建这样的 main()方法:

After years of Java programming I always used to create my main() methods like this :

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

但是最近我从网上学习了一些代码并且有时看到这个代码而不是通常 main()上面使用:

But recently I studied some codes from the Web and saw this sometimes instead of the usual main() use above :

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

我只是想知道:


  • 为什么要用这个而不是通常的 main()方式?当我试一试时,我看不出任何差异。

  • 这两种方式有什么区别?

  • Why to use this instead of the usual main() way ? I can't see any difference when I give it a try.
  • What is the difference between these two ways ?

感谢您阅读我和您的答案。

Thanks for reading me and your answers.

推荐答案

文档解释了原因。来自初始主题

The docs explain why. From Initial Threads


为什么初始线程不能简单地创建GUI本身?因为几乎所有创建Swing组件或与Swing组件交互的代码都必须在事件派发线程上运行。

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.

事件派遣线程


一些Swing组件方法在API规范中标记为线程安全;这些可以从任何线程安全地调用。 必须从事件派发线程调用所有其他Swing组件方法。忽略此规则的程序可能在大多数时间内正常运行,但会遇到难以重现的不可预测的错误。

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

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