I’m using Netbeans IDE to make a gui application. I have a JFrame with a JPanel inside it. After a button click I want to display a different JPanel inside the first. The other JPanel is in a different file. How would I go about doing this? If this is not practical I don’t mind replacing the first JPanel with the second one.
I’ve tried the following but it doesn’t seem to work. I’m new to Java and Gui programming so I would appreciate any help I can get.
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
JPanel2 jPanel2 = new JPanel2();
JPanel1.add(jPanel2);
}
See the javadoc of the
Container#addmethod:So it is not sufficient to add the panel, but you must also validate the hierarchy again, e.g. by calling
Using a
CardLayoutas @Andrew suggested in his answer is probably a better alternative then manually replacing panelsTwo side-notes:
JPanel1.addcall would becomejPanel1.addJxxxSwing classes. Looking at your class namesJPanel1andJPanel2you are exactly doing that. It is better to use the available API to customize those classes then to extend them.