1

I am new to Java Swing GUI development. In some sample code, I see Swing window is shown with the EventQueue.invokeLater():

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            MainWindow window=new MainWindow();
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.setVisible(true);                
        }
    });

    System.out.println("main exited");

}

But as I tried, I can also show a window without using EventQueue.invokeLater():

public static void main(String[] args) {

    MainWindow window=new MainWindow();
    window.setDefaultCloseOperation(EXIT_ON_CLOSE);
    window.setVisible(true);    

    System.out.println("main exited");

}

So what's the difference? When should I use each method?

smwikipedia
  • 61,609
  • 92
  • 309
  • 482

1 Answers1

4

When invoking code from the main() method you should ALWAYS use the EventQueue.invokeLater() because all Swing components should be created on the Event Dispatch Thread (EDT).

Yes, the code will work 99.99% of the time when creating a simple GUI the other way, but you don't want to waste time debugging a random bug when it doesn't work.

Read the section from the Swing tutorial on Concurrency and Swing for more information about the EDT and why Swing components should be created on the EDT.

Note, code executed from a Swing listener is invoked from the EDT.

camickr
  • 321,443
  • 19
  • 166
  • 288