0

I am creating a program which currently has 3 classes. These include the JFrame class in addition to the 2 other JPanel classes. Does anyone know how I can make a JButton in one JPanel class remove that specific JPanel and have the JFrame add in a new JPanel (from another class)?

For example, let's say that the JFrame class is called frame, and the two JPanel classes are called panel1 and panel2. If a button is clicked in panel1, how do you tell the frame to remove panel1 and add panel2?

user1546859
  • 240
  • 2
  • 10

1 Answers1

1

Well it depends from what you mean with the "remove" word.

A good approach will be to use the MigLayout using the hidemode property. The initial state of your form will contain both panels in the JFrame ,but the second panel will be invisible.

When you press the button of the first JPanel, it will set the visibility of this panel to false, and the visibility of the second panel to true.

On the other hand, if you want to remove completely from the frame the first panel, give a name to it using the method panel.setName(panelsName), and then retrieve every sub-component of the JFrame and put them in a collection.

Then iterate through this collection, and check for the name of every component.

If component.getName().equals(panelsName) then use the frame.remove(component) method to get rid of it. After that, it is possible that you have to call validate and repaint in your frame, though I am not sure if it is necessary. Just try it out;)