1

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);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Indy411
  • 3,666
  • 4
  • 20
  • 19

4 Answers4

6

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:

  • Learn and respect Java naming conventions (e.g. instances of a class start with a lowercase). so your JPanel1.add call would become jPanel1.add
  • There is in most cases no need to extend the 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.
Robin
  • 36,233
  • 5
  • 47
  • 99
3

You will also have to add the following code such as your changes to take effect:

jPanel1.validate();
jPanel1.repaint();
Dan D.
  • 32,246
  • 5
  • 63
  • 79
3

Use a CardLayout, as shown here.

Game view High Scores view

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • +1 Good suggestion for the `CardLayout`. After seeing the code I forgot about the initial requirement or I would have suggested that myself (will update my answer immediately) – Robin Sep 19 '12 at 09:35
  • @mKorbel indeed, forget even doing that. Corrected – Robin Sep 19 '12 at 10:33
0
    newPanel obj = new newPanel ();
    setLayout(new BorderLayout());
    add(obj ,BorderLayout.EAST ,1);//3rd argument is index
    repaint();
    revalidate();