Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: single frame vs multiple frames

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?

like image 406
user1221297 Avatar asked Feb 22 '23 10:02

user1221297


1 Answers

Destroying the main JFrame would be silly -- not to mention jarring for the user. Just use a single JFrame and change its contents.

To implement an installer wizard, use a single JFrame containing one large JPanel on top and a smaller one containing the "Next", "Back", "Cancel" buttons along the bottom. When the Next or Back buttons are pressed, you replace the large JPanel. You can have many different JPanel subclasses, one for each "page" of the wizard.

There's a LayoutManager called CardLayout which is ideal for implementing this scenario -- it manages a "stack" of components, and only shows one of those components at a time. Use a BorderLayout in the JFrame. Into the center position put a JPanel with a CardLayout. Then add the individual pages of the wizard to that JPanel, so the CardLayout can manage them.

like image 156
Ernest Friedman-Hill Avatar answered Mar 03 '23 22:03

Ernest Friedman-Hill