开发者

Does this code run on the EDT?

given the following code:

public class MainFrame extends JFrame{

  public MainFrame() throws HeadlessException {
    super();
    this.setSize(500, 400);
    this.setVisible(true);
    this.setDefaultCloseOperation(DISPOSE_O开发者_运维技巧N_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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜