Use singleton Application classes

Swing GUI applications are usually a mix of business, GUI and data model code. Since most applications contain some sort of “main frame”, I’ve seen many applications with the main method in the MainFrame class.

Most applications use some sort of global configuration, and it is not unusual to find initialization code also in the MainFrame class, along with a lot of methods used for centralized event/error processing and similar.

Try to separate the presentation (visual) code from your application or business logic. The frame class should be concerned only with setting up the layout of the components and linking them to the right event handlers (see MVC).

Do not put initialization code or centralized event/error handling methods into your MainFrame class. Put the initialization code and all application-specific methods into a static singleton Application class. That class is also a good candidate to hold the main method. Components can ask the Application class for the main window reference when displaying dialogs (see Modal JDialog In Applet and Always Set Parent For Modal Dialogs), you have gained the flexibility to work with multiple frames, and you can convert the application to an applet by changing a few lines of code.

 

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  best/use_singleton_application.txt · Last modified: 2005/02/14 10:52
 
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register