I'm using several sources to try to get started with Swing. The Sun Java Tutorials usually hava a static main method that calls a second static method (createAndShowGUI) in which the class constructor is called, a JFrame component is instantiated, and the content pane filled. In examples from other sources, the main method calls a regular method, which does the initial setup. My understanding of OOP is shaky. Can someone help me sort out the differences / advantages and disadvantages of these techniques? Thanks Robert
You really ought to call a 2nd method, but I don't like the way the Java Tutorial does it in a static context. I think this is the best way to do it, actually quite similar to what you have seen in the Java Tutorials: You will find I shamelessly copied that lot from here. I tend to use the 2nd of those options. You may not actually need to pass args. You will probably set up all the components in the constructor, and the bits about setSize, setDefaultCloseOperation and setVisible can go in the showGUI method.
The reason is that you have to handle all Swing components from a single thread, and that includes Events. Using the event dispatch thread means that the components and events run on the same thread. Anything which takes a long time (eg long calculations, multiple bouncy ball animations) needs a separate thread of its own, but setting up new threads is probably more advanced than what you are interested in at present.
The tutorial schema is a way to insure that an application is realized and ready to go before any of its components begin sending events. There are times when events can be sent before the app is ready to deal with them, eg, events from MouseMotionListeners and ComponentListeners. Since these issues can be difficult to explain to those who are newer to java it is easier to say "always do this and you'll be okay."
Joined: Oct 13, 2005
Thank you, Craig. I always find your answers helpful.