tags:

views:

79

answers:

2

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

  1. Using java.awt.EventQueue.invokeLater() in main();
  2. Using SwingUtilities.invokeLater() in main();
  3. not bothering with threads at all, simply instantiating the JFrame subclass and calling setVisible(true) from main without wrapping it inside a Runnable; this seems to work anyway.

Thanks.

+2  A: 

SwingUtilities.invokeLater just calls EventQueue.invokeLater. The latter was introduced in Java 1.2. Before that Swing had a hack where it repainted a window to get onto the EDT. I would suggest that java.awt.EventQueue is the logical place for this method, and the sensible one to call. However, the relationship between Swing and AWT is seriously messed up.

There is very little need to subclass JFrame, and it is generally bad practice. But bad practice is the standard for Swing. Running multithreaded like that you can potentially run into problems, although you might get away with it on your own machine. The worst possible thing you can do is a bit of initialisation on the EDT and a bit on the main thread (for a while it was 50/50 whether FindBugs (of all programs) would start on a single hardware-threaded machine).

Tom Hawtin - tackline
"There is very little need to subclass JFrame, and it is generally bad practice." - now this got me interested. NetBeans did this for me automagically when creating the app skeleton. Can you please elaborate on why this is a Bad Thing?
neuviemeporte
Don't quite see the problem with subclassing JFrame. If what you need logically is a subclass of JFrame, create a subclass of JFrame...
Neil Coffey
You very, very rarely need a *subclass* of `JFrame`. Just like you very rarely need a subclass of `Thread`.
Tom Hawtin - tackline
@Tom: While I agree WRT Thread, please defend that statement for JFrame.
Software Monkey
I think this is what Tom means: http://stackoverflow.com/questions/1143923/why-shouldnt-you-extend-jframe-and-other-components
neuviemeporte
+2  A: 

The thing to bear in mind with threading is that "seems to work" isn´t the same as "will demonstrably work under all circumstances".

The basic rule is you shouldn´t create Swing/manipulate components outside the event thread, and application's main thread is "outside the event thread". So in your application startup code, you should create your main window in an invokeLater().

If you're programming with Swing, I would use the SwingUtilities version of invokeLater(). Even though I think functionally in current implementations one just calls the other, I guess this could change in the future.

Neil Coffey