6

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

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();
        }
    });
}

}

4

1 回答 1

8

只有第二种方法是正确的。Swing 组件只能在事件调度线程中创建和访问。请参阅swing 中的并发。相关报价:

为什么初始线程不简单地创建 GUI 本身?因为几乎所有创建或与 Swing 组件交互的代码都必须在事件调度线程上运行。下一节将进一步讨论此限制。

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

于 2013-09-24T08:56:53.093 回答