在 Java/Swing 中,可以创建新的“main”吗?用户何时需要 JPanel 对象?
我很好奇每次用户希望从后续 JPanel 返回到该 JPanel 时创建一个新的主 JPanel 对象是否是一个好习惯?
仅供参考,我的 Swing 应用程序有一个 JFrame,其第一个对象是带有三个 JButton(其中一个是“审阅”按钮)的 mainJPanel。
假设用户按下“审阅”按钮。该程序在 JFrame 的内容窗格上调用removeall(),并创建一个新的 reviewJpanel 对象,该对象具有 JTable 和 JButton(我们称之为 Finish Review)。
假设用户完成审阅并按下“完成审阅”按钮。该程序的目的是返回到 mainJPanel 屏幕,因此它创建了一个与上面第 2 段中完全相同的新 mainJPanel 对象。
我想知道每次创建一个新的 mainJPanel 对象是否多余?但是,如果我要以某种方式保留 mainJPanel,当用户按下 Finish Review 按钮时,如何从 JFrame 中删除 reviewJPanel?
我希望这些问题对刚接触 Swing 的其他用户有用。我有几本 Swing 书籍,遗憾的是它们似乎忽略了处理“主”JPanel 和多个后续 JPanel 以及来回切换的问题。
I am curious whether it is good practice to make a new main JPanel object every time a user wishes to return to that JPanel from a subsequent JPanel?
FYI, my Swing application has a JFrame whose first object is a mainJPanel with three JButtons (one of them is a Review button).
Let's say the user pushes the Review button. The program calls removeall() on the JFrame's content pane and creates a new reviewJpanel object which has a JTable and a JButton (let's call it Finish Review).
Let's say the user finishes reviewing and pushes the Finish Review button. The program's intention is to return to the mainJPanel screen, so it creates a new mainJPanel object exactly the same as in para 2 above.
I am wondering if is it redundant to make a new mainJPanel object each time? But if I were to keep the mainJPanel somehow, how could I remove the reviewJPanel from the JFrame when the user pushes the Finish Review button?
I hope these questions are useful for other users new to Swing. I have a couple of Swing books and regrettably they seem to overlook the question of handling "main" JPanels and multiple subsequent JPanels and switching back and forth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果一次只有一个面板,只需使用
setContentPane
更改面板即可。首次创建框架时,请执行frame.setContentPane(mainJPanel);
。然后,当用户单击按钮时,执行frame.setContentPane(otherPanel);
。mainJPanel
将被新面板替换,当用户完成后,您可以再次使用frame.setContentPane(mainJPanel);
将主面板放回原处。您不必浪费资源重新创建面板,而且它比使用removeAll
并添加新面板更快、更高效。If you only have one panel at a time, just change panels with
setContentPane
. When you first create your frame, doframe.setContentPane(mainJPanel);
. Then, when the user clicks a button, doframe.setContentPane(otherPanel);
. ThemainJPanel
will be replaced by the new panel, and when the user is done, you can useframe.setContentPane(mainJPanel);
again to put the main panel back. You don't have to waste resources recreating the panel, and it's faster and more effecient than usingremoveAll
and adding the new panel.