为什么要使用单独的线程在JAVA中显示GUI [英] Why should I use a separate thread to show a GUI in JAVA

查看:69
本文介绍了为什么要使用单独的线程在JAVA中显示GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的问题使我感到困惑.您可以通过设置框架的 setVisible 属性 true 来显示JAVA GUI应用程序.但是,在我在互联网上发现的几乎所有示例中,它们都使用单独的线程来执行相同的操作.

This simple issue confuses me. You can display a JAVA GUI application by setting the frames' setVisible property true. But in almost all the examples I found on internet they use a separate thread to do the same thing.

他们这样做,

SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        new Frame().setvisible(true);  //just take the idea of this line
    }
});

我发现这两种方法之间没有区别.但是必须有一些特殊的原因,这就是每个人都这样做的原因.

I found no difference between the two methods. But there must be some special reason, that's why everyone is doing this.

有人可以解释一下..谢谢!

Can someone explain it..thanks!

推荐答案

以这种方式启动应用程序的主要原因是,Swing组件不是线程安全的,因此您需要保证GUI的线程将从以下线程开始:称为事件调度线程"( EDT )的线程.如果不这样做,则无法确定它将在哪个线程中启动,但是正如几种注释器所指出的那样,保证主线程不是 EDT.

The main reason for launching your application in this way is that Swing components are not thread-safe so you need to guarantee which thread your GUI will start from: the one called the Event Dispatching Thread (EDT). Without doing this, you can't be sure what thread it will start in, but as noted by several kind commentators, the main thread is guaranteed not to be the EDT.

您应仅在EDT中创建,访问或修改UI组件.否则,将导致意外的行为(如果幸运的话)和/或重新绘制.

You should only create, access, or modify UI components from within the EDT. Doing otherwise will result in unexpected behavior (if you're lucky) and/or dirty repaints.

一些资源,我建议您熟悉:

Some resources I suggest you become familiar with:

您还可以阅读 更新

这是博客我一直在寻找:P

This is the blog I've been trying to find :P

这基本上解释了为什么在开始之前将您的 main 与EDT同步很重要的原因,并且还描述了一些有关为什么的细节.

This basically explains why it's important to sync your main with the EDT before getting started, it also describes some of the details about why.

它还描述了为什么许多开发人员在启动应用程序时会犯此根本性错误(基本上,我们被告知可以这样做,但实际上我们从未被允许...对我们不利)

It also describes why many developers make this fundamental mistake when starting their applications (basically, we were told we could, but we never were really allowed to...bad us)

这篇关于为什么要使用单独的线程在JAVA中显示GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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