显示 Java GUI 是否需要一些特殊处理? [英] Does displaying Java GUI requires some special treatment?

查看:37
本文介绍了显示 Java GUI 是否需要一些特殊处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一些 Java 图形用户界面示例代码,我想知道显示图形用户界面的正确方法是什么.假设为某个 GUI 编写了 createAndShowGUI() 方法.我看到了这样的:

I was looking at some example code of GUIs in Java, and I was wondering what the proper way to display a GUI. Suppose a createAndShowGUI() method is written for some GUI. I saw something like this:

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

在没有 javax.swing 的东西的情况下,在 main 方法的末尾简单地调用 createAndShowGUI() 会是错误的吗?或者我想我真正的问题是这里发生了什么.我对线程很熟悉,但我不确定为什么需要创建一个新线程(这就是这里发生的事情吗?)来显示 GUI.

Would it be wrong simply to call createAndShowGUI() at the end of the main method without the javax.swing stuff? Or I guess my real question is about what is going on here. I'm familiar with threads but I am not sure why it's necessary to make a new thread (is that what's going on here?) to display the GUI.

推荐答案

所有与 UI(Swing 或 AWT)的交互都必须在事件调度线程的上下文中执行.

All interactions with the UI (Swing or AWT) MUST be executed from within the context of the Event Dispatching Thread.

Swing(和 AWT)组件不是线程安全的,从 EDT 之外的任何线程更改它们中的任何一个都可能导致更新损坏、绘制技巧、死锁并可能使 VM 崩溃.它们也出了名的难以调试.

Swing (and AWT) components are not thread safe, changing any of them from any thread other the EDT can lead to corrupted updates, paint artifices, dead locks and possibly crash the VM. They are also notoriously difficult to debug.

你可能想通读一遍

我还应该补充一点,当 main 方法被执行时,它运行在虚拟机为其创建的任何线程中.这保证不是 EDT,因为它在需要之前不会开始.

I should also add, when the main method is executed, it is running in what ever thread the VM created for it. This is guaranteed not to be the EDT, as it will not have begin started until it is needed.

这就是为什么好的 Swing 程序总是从类似 EventQueue.invokeLater 开始.您也可以使用 SwingUtilities.invokeLater,但它通常是一样的.

This is why good Swing programs always start with something like EventQueue.invokeLater. You could also use SwingUtilities.invokeLater, but it's generally the same thing.

这篇关于显示 Java GUI 是否需要一些特殊处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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