问题
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?
回答1:
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.
回答2:
The CardLayout is well suited for this. You just swapout the JPanel contents when the "Next" button is pressed.
来源:https://stackoverflow.com/questions/9363359/java-single-frame-vs-multiple-frames