I am curious as to the differences between the following approaches to creating a Swing window:
- Using java.awt.EventQueue.invokeLa开发者_JAVA百科ter() in main();
- Using SwingUtilities.invokeLater() in main();
- 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.
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.
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).
精彩评论