开始挥杆应用程序的最佳实践 [英] Best practice to start a swing application

查看:111
本文介绍了开始挥杆应用程序的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动java swing应用程序的最佳实践方法是什么?也许有另一种方法可以做到这一点。

What is the best practice way to start a java swing application? Maybe there is another way to do it.

我想知道我是否必须使用SwingUtilities类来启动应用程序(可能性)(第一种可能性) 。

I want to know if i have to use the SwingUtilities class to start the application (secound possibility) or not (first possibility).

public class MyFrame extends JFrame {

public void createAndShowGUI() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    // add components and stuff
    this.setVisible(true);
}

public static void main(String[] args) {

    // First possibility
    MyFrame mf = new MyFrame();
    mf.createAndShowGUI();

    // Secound possibility
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            MyFrame mf = new MyFrame();
            mf.createAndShowGUI();
        }
    });
}

}

推荐答案

只有第二种方法是正确的。必须仅在事件派发线程中创建和访问Swing组件。请参阅摆动并发。相关引用:

Only the second way is correct. Swing components must be created and accessed only in the event dispatch thread. See concurrency in swing. The relevant quote:


为什么初始线程不是简单地创建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. This restriction is discussed further in the next section.

所以是的,你需要使用 invokeLater()

So yes, you need to use invokeLater().

这篇关于开始挥杆应用程序的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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