Search code examples
javauser-interfacerunnable

Difference between using runnable to make GUI vs Anonymous object


I couldn't any other threads that answer this question, but I'm wondering what's the difference between let's say:

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

or:

public static void main(String[] args) {
     SwingUtilies.invokeLater(new Runnable() {
           public void run() {
              new GUIObject();
           }
      });
 }

I have been doing the first all this time, but I see some videos on YouTube that does the latter, and it seems to do the same thing.


Solution

  • Your Swing GUI needs to run on the the Event Dispatch Thread (EDT). The main function, when started by the Java VM, is not on the EDT. So it's up to you to make sure your GUI starts on the EDT by using invokeLater().

    What might be confusing is that if you don't use invokeLater() things will probably still work. So what's all the fuss? Well, one day, when you least expect it, things won't work and this will be the cause.

    More info can be found here: Initial Threads.