views:

41

answers:

1

Hi folks,

  1. 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?

  2. FYI, my Swing application has a JFrame whose first object is a mainJPanel with three JButtons (one of them is a Review button).

  3. 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).

  4. 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.

  5. 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?

  6. 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.

+4  A: 

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.

qmega
Many thanks for the advice, it's quite handy!
Arvanem