Jeremy Stein - Journal
« Swing Stinks | The height of danger » |
Best Practices for Swing
After many bruises, I think I’ve come up with the best approach for general class structure in a Swing application.
Many of the demos in the Swing Tutorial simply extend JFrame or JDialog and implement Listener. The class’s constructor creates the components and places them on the frame. The class acts as the listener for any events it generates. The problems with this approach:
1) You don’t really want your class to be the listener. Would you want other classes to register your class as listening to their events? But even if you were to move the listener to a private nested class (as it should be)…
2) You don’t have any control over how your frame is used. You inherit all of the JFrame or JDialog methods, like show, hide, etc. It’s clunky to override those, when really you should be shielding access to them.
I think this calls for composition rather than inheritance. Create a class that constructs the frame or dialog. Clients talk to that class to perform any action. One advantage of this approach is that the class can defer initialization to the first reference without any effect on the client. For example, the class could have a show method to display the dialog. This show method would check if the private JDialog member was null. If so, it would initialize it.
I really ought to add some code examples here. Email me if you’d like to see an example. Someone did email me, so I’ve posted an example.
No Comments
Be the first to comment!
Leave a Reply