1

考虑这两个类,你能解释一下它们之间的区别吗?我知道第一个创建类的对象,但这不是我关心的……特别是代码块,包括和下面的行,** javas.swing.swingUtiliies.invokeLater(new Runnable() {

//也都导入javax.swing

public class HelloWorld extends JFrame{
public HelloWorld(){
    super("HelloWorldSwing");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Hello World");
    getContentPane().add(label);

    pack();
    setVisible(true);
}

public static void main(String[] args) {
    HelloWorld h = new HelloWorld();
}
}

public class HelloWorldSwing {

private static void createAndShowGUI() {
    JFrame frame = new JFrame("HelloWorldSwing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Hello World");
    frame.getContentPane().add(label);

    frame.pack();
    frame.setVisible(true);
}

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

1 回答 1

3

The second example upholds the rule to execute all GUI-related code on the Event Dispatch Thread, which is achieved by passing a Runnable with said code to the invokeLater method.

By "GUI-related code" I mean instantiating any AWT/Swing classes, calling any methods on them or accessing any properties.

于 2013-08-06T19:58:55.043 回答