Java: single frame vs multiple frames

我的梦境 提交于 2020-01-13 04:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!