Manny P
Manny P

Reputation: 33

? concerning running GUI classes..please assist

Consider the two classes and could you offer an explanation on the difference between them.. I know the first creates an object of the class but that is not my concern... Specifically the block of code including and below the line with, **javas.swing.swingUtiliies.invokeLater(new Runnable() {

//also both import 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();
        }
    });
}
}

Upvotes: 1

Views: 60

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

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.

Upvotes: 3

Related Questions