-
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.
I am curious whether it is good practice to make a new main JPanel
Share
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);. ThemainJPanelwill 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 usingremoveAlland adding the new panel.