tags:

views:

35

answers:

1

given the following code:

public class MainFrame extends JFrame{

  public MainFrame() throws HeadlessException {
    super();
    this.setSize(500, 400);
    this.setVisible(true);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    JButton myButton = new JButton("Test");

    this.add(myButton);

    this.pack();

  }

  public static void main(String[] args) {     
    new MainFrame();
  }

}

Does the code inside the constructor run on the EDT. I think it does because it's executed "inside" an instance of a JFrame, but I need a second opinion.

Continuing the idea, If I were to create other controls, for example in the main() function, that code wouldn't be on the EDT?

Thank you!

+1  A: 

No. You are calling the constructor from the main method which runs on the main thread.

Add the usual boilerplate:

public static void main(String[] args) {     
    java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
        new MainFrame();
    }});
}

Also it's generally a bad idea to extend classes that you don't need to (including JFrame, JPanel and Thread). There is no need to declare HeadlessException as it is unchecked.

Tom Hawtin - tackline
So, If I were to call SwingUtilities.invokeLater in main() to instantiate the Frame would that be ok?
Bogdan
I saw in you edited example that you used EventQueue. Is this recommended against SwingUtilities?
Bogdan
@Bogdan `SwingUtilities.invokeLater` just calls `EventQueue.invokeLater`, as explained http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)
Shakedown
Ok. Got it. Thanks a lot guys!
Bogdan
@Bogdan In Java 1.1, AWT did not have `EventQueue.invokeLater`, so the Swing extension (as was) had to implement `invokeLater` using a hack. IMO, from Java 1.2 there is no need to reference the dustbin of `SwingUtilities` when dealing with AWT's `EventQueue`. OTOH, there is a fair bit in `javax.swing` which is really to do with AWT whether you are using Swing or not, so as it is a mess anyway it probably doesn't make a huge difference which you choose.
Tom Hawtin - tackline