Question

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.

Était-ce utile?

La 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.

Autres conseils

invokeLater takes a Runnable that is placed in the Event Dispatch Thread queue, where it will eventually be ran on the EDT. People modify and query state of Swing objects on the EDT only because Swing is not thread safe, so the concurrency issues between modifying non-thread-safe objects from one thread to another don't exist if you always use the same single thread. It may be rare in your experience that your Swing code doesn't break when using threads other than the EDT, but it's possible that it will.

This practice of eliminating threading issues by using the same thread to modify and query state on a set of objects is called thread confinement. It's a tricky practice because it requires users of those objects to keep the practice up in their own application code (such as when you do use invokeLater for Swing).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top