Java – Design pattern for window management in a Java Swing app

design-patternsguijavaswing

I've just started creating my very first little Java Swing app. When the program opens, it brings up a single, simple window with a label and a couple buttons. Clicking one of those buttons is supposed to wipe out the welcome screen and replace it with a totally different panel.

I'm not sure what the best way to create that functionality is. One method would be to pass my JFrame as an argument into… just about every other component, but that feels hacky to me. Or, there's making each panel double as an action listener, but that doesn't seem right, either.

Is there a design pattern I should be applying here? "Replace the contents of the main — and only — window" must be a reasonably common operation. A name for the pattern would be enough; I can use Google on my own from there. (I wouldn't say no to a longer explanation, though.)

Best Answer

When building Swing apps, I usually base it on the Mediator Pattern. In this pattern, a Mediator class (usually the main JFrame) handles the different GUI parts (usually the JPanels, JMenus...) and takes care of communication between them.

For example, if an event occurred in JPanel1, JPanel1 notifies the mediator (the JFrame). the JFrame then takes action by modifying JPanel2.

FYI: all my projects were small-to-mid GUI apps, so I'm not sure this patterns scales well. But if you could design an adequate architecture, the Mediator pattern can be a solid base.

Related Topic