Search code examples
javaswingswingutilitiesinvokelater

What is SwingUtilities.invokeLater


Possible Duplicate:
What does SwingUtilities.invokeLater do?
SwingUtilities.invokeLater

I have seen this little piece of code hundreds of times:

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

Now my question is: what does invokeLater() do? What kind of bad things will happen if I just create and show my GUI inside the main thread?


Solution

  • Nothing bad will happen if you're updating it from the EDT while following guidelines.

    That is...

    If invokeLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the doRun.run() will still be deferred until all pending events have been processed.

    Source

    If that isn't the case, invokeLater() is required.

    It schedules a Runnable which will be executed on the EDT (event dispatching thread).