Think about the classic installation process, where you have a “next” button and when you click it the content of the window changes. To represent this situation I thought of two possible solutions:
-when “next” is clicked destroy the current JFrame and create a new JFrame, maybe passing to his constructor useful information (e.g. actual window size, content inserted by the user in the current frame, …)
-when “next” is clicked remove all the components from the current JFrame and add new components as needed
The first solution looks way better about OOprogramming, because I can keep separate classes for different frames and I can avoid huge methods that empty the frame and repopulate it. However the first solution sounds a bit “dirty” and I should pass lots of parameters to the new frame. To represent this situation I would choose the second solution.
Now think about a menu with an “option” component: in this situation I would create a new JFrame when “option” is clicked, so that I can populate it with option items. Is this a correct solution? Is there a way I can always know which one is the best solution? Are there any solutions I didn’t think about?
Destroying the main
JFramewould be silly — not to mention jarring for the user. Just use a singleJFrameand change its contents.To implement an installer wizard, use a single
JFramecontaining one largeJPanelon top and a smaller one containing the “Next”, “Back”, “Cancel” buttons along the bottom. When theNextorBackbuttons are pressed, you replace the largeJPanel. You can have many differentJPanelsubclasses, one for each “page” of the wizard.There’s a
LayoutManagercalledCardLayoutwhich is ideal for implementing this scenario — it manages a “stack” of components, and only shows one of those components at a time. Use aBorderLayoutin theJFrame. Into the center position put aJPanelwith aCardLayout. Then add the individual pages of the wizard to thatJPanel, so theCardLayoutcan manage them.