I am curious whe开发者_如何学Cther 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.
If you only have one panel at a time, just change panels with setContentPane
. When you first create your frame, do frame.setContentPane(mainJPanel);
. Then, when the user clicks a button, do frame.setContentPane(otherPanel);
. The mainJPanel
will be replaced by the new panel, and when the user is done, you can use frame.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 using removeAll
and adding the new panel.
精彩评论