Reputation: 3766
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);
}
Upvotes: 1
Views: 10163
Reputation: 73
newPanel obj = new newPanel ();
setLayout(new BorderLayout());
add(obj ,BorderLayout.EAST ,1);//3rd argument is index
repaint();
revalidate();
Upvotes: 0
Reputation: 36601
See the javadoc of the Container#add
method:
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.
So it is not sufficient to add the panel, but you must also validate the hierarchy again, e.g. by calling
JPanel1.validate();
JPanel1.repaint();
Using a CardLayout
as @Andrew suggested in his answer is probably a better alternative then manually replacing panels
Two side-notes:
JPanel1.add
call would become jPanel1.add
Jxxx
Swing classes. Looking at your class names JPanel1
and JPanel2
you are exactly doing that. It is better to use the available API to customize those classes then to extend them.Upvotes: 6
Reputation: 32391
You will also have to add the following code such as your changes to take effect:
jPanel1.validate();
jPanel1.repaint();
Upvotes: 3