What is the difference between Swing window initialization methods?

I am curious about the differences between the following approaches to creating a Swing window:

  • Using java.awt.EventQueue.invokeLater () in main ();
  • Using SwingUtilities.invokeLater () in main ();
  • not bothering threads at all, just instantiating a JFrame subclass and calling setVisible (true) from main, without wrapping it inside a Runnable; it works anyway.

Thank.

+2


source to share


2 answers


Something to keep in mind when streaming is that "seems to work" is not the same as "will obviously work under all circumstances."

As a general rule of thumb, you should not create Swing / manipulate components outside the event flow, but the main application thread is "outside the event flow". Thus, in your application startup code, you must create your main window in invokeLater ().



If you are programming with Swing, I would use the SwingUtilities version of invokeLater (). While I think functionally in current implementations is just calling another, I think this may change in the future.

+3


source


SwingUtilities.invokeLater

just calls EventQueue.invokeLater

. The latter was introduced in Java 1.2. Before that, Swing had a hack where he repainted the window to get to EDT. I would guess that there java.awt.EventQueue

is a logical place for this method and sane to call. However, the relationship between Swing and AWT is seriously confused.



There is JFrame

very little subclass and it is generally bad practice. But bad practice is the standard for swing. You may run into problems doing multithreading, although you can get away with it on your machine. The worst thing you can do is initialize the EDT a little and a little on the main thread (it was 50/50 for a while, will FindBugs (of all programs) run on a single hardware-threaded computer).

+3


source







All Articles