你如何使用Event Dispatch Thread? [英] How do you use the Event Dispatch Thread?

查看:379
本文介绍了你如何使用Event Dispatch Thread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解了swing如何不是线程安全的。深入研究,我发现对swing组件的每次修改都必须在Event Dispatch Thread上完成,以防止与多线程相关的各种问题。然而,信息似乎完全停在那里。似乎没有一个好的教程可以解释如何在互联网上的任何地方进行此操作。

I learned about how swing isn't thread-safe. Delving deeper, I discovered that every modification to a swing component must be done on the Event Dispatch Thread in order to prevent various issues associated with multithreading. However, the information seemed to completely stop there. There doesn't seem to be a good tutorial that explains how to do this anywhere accessible on the internet.

将与其他问题相关的代码中的信息拼凑起来,它似乎我不得不在我的程序中的每一个swing修改周围放置一个不整齐的代码块(比如我自己的代码中的这个例子):

Patching together information from code posted in relation to other issues, it seemed that I would have to put an untidy block of code around every single swing modification in my program (like this example from my own code):

try {
        SwingUtilities.invokeAndWait(new Runnable() {

            public void run() {
                setTitle("Frame title");
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setVisible(true);

                setSize(800, 480);
                setLocationRelativeTo(null);
                setIconImage(Toolkit.getDefaultToolkit().createImage(ClassLoader.getSystemResource("Frame icon.png")));
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

基本上,这是对的吗?我是否必须在代码中对Swing组件的每次修改周围放置代码(或与invokeLater等效的代码)?

Basically, is this right? Do I have to put that code (or the equivalent with invokeLater) around every modification to a Swing component in my code?

另外,为什么Swing不会自动执行此操作?

Also, why doesn't Swing do this automatically?

推荐答案

诀窍是,当挥动召唤你时,它总是会在EDT中,所以你不必担心关于它。

The trick is that when swing calls you it will ALWAYS be in the EDT, so you don't have to worry about it.

但是如果你在一个计时器或一些其他外部事件触发的动作,你的主线程或你创建的任何其他线程然后是,你必须使用invokeLater或invokeAndWait。

However if you are in a timer or an action triggered by some other external event, your main thread or any other thread you've created then yes, you have to use invokeLater or invokeAndWait.

换句话说,是的swing会自动执行it。需要使用invokeXx是非常罕见的,如果在内部进行swing会浪费太多时间。

In other words, yes swing does do "it" automatically. Needing to use invokeXx is so rare that if swing were to do it internally it would waste too much time.

许多java程序员从来没有想过这个,它可能会导致一些漂亮的绘制GUI时难以发现难以发现的问题。我希望当你不使用EDT调用它时,swing会抛出一个例外 - 如果专业的GUI出现,那么Java会有更好的声誉,因为那里会有更少的废话。

Many java programmers never figure this out and it can cause some pretty nasty hard-to-find problems with drawing your GUI. I do wish swing threw an exception when you called it not using the EDT--Java would have a better reputation when it came to professional GUIs if it did because there would be less crap out there.

这篇关于你如何使用Event Dispatch Thread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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