1

I was looking at some example code of GUIs in Java, and I was wondering what the proper way to display a GUI. Suppose a createAndShowGUI() method is written for some GUI. I saw something like this:

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

Would it be wrong simply to call createAndShowGUI() at the end of the main method without the javax.swing stuff? Or I guess my real question is about what is going on here. I'm familiar with threads but I am not sure why it's necessary to make a new thread (is that what's going on here?) to display the GUI.

CowZow
  • 1,275
  • 2
  • 17
  • 36
  • It's safer to take measures to display your GUI on the Swing event thread. You may be able to display it just in the main, but then again, you may run into problems too, and I've seen it happen too. – Hovercraft Full Of Eels Nov 27 '12 at 04:36
  • 2
    *"I'm familiar with threads but I am not sure why it's necessary to make a new thread (is that what's going on here?) to display the GUI."* That code does not so much 'make a new thread' as ensure the construction of the GUI is done on the Event Dispatch Thread. – Andrew Thompson Nov 27 '12 at 04:37

2 Answers2

2

All interactions with the UI (Swing or AWT) MUST be executed from within the context of the Event Dispatching Thread.

Swing (and AWT) components are not thread safe, changing any of them from any thread other the EDT can lead to corrupted updates, paint artifices, dead locks and possibly crash the VM. They are also notoriously difficult to debug.

You might like to have a read through

I should also add, when the main method is executed, it is running in what ever thread the VM created for it. This is guaranteed not to be the EDT, as it will not have begin started until it is needed.

This is why good Swing programs always start with something like EventQueue.invokeLater. You could also use SwingUtilities.invokeLater, but it's generally the same thing.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Because everything related to a GUI should be done through the Event Dispatch Thread (EDT), that is how Java manages the whole drawing of interfaces. Basically the method delegates the execution of the run() method of the passed Runnable object to the correct thread.

Mind that Runnable is not a Thread, it's just an interface to provide a method that does something (hence the class is runnable). But there is no thread involved here, the fact that Thread extends from Runnable is just because a thread is also a Runnable object in the sense that can execute something.

Jack
  • 131,802
  • 30
  • 241
  • 343