views:

504

answers:

2

I have a class that extends javax.swing.JPanel, it contains a single JButton. I've created the class in NetBeans designer. As such, I have a initComponents() function thats called from the class constructor.

What I want to do is when/if a function is called, I want to add a second button, and change the layout of the two buttons. Doing simply:

public void addSecond() {
    javax.swing.JButton secondButton = new javax.swing.JButton();
    add(secondButton , java.awt.BorderLayout.CENTER);
}

Doesnt work, the new button doesnt show up. I tried a call to invalidate() as well but no luck.

  • How do I trigger a re-evaluation of the layout?
  • If said function is called more than once, what parts of the layout/buttons do I need to call dispose() on? Any other cleanup I should worry about?
  • Would this be easier to handle if I don't use the NetBeans designer?
+1  A: 

when you changed the components in a way that changes the layout, you need to trigger the layout manager again by calling revalidate(). You can call it as often as you want.
For simple layouts just calling repaint() may be sufficient.

And actually unless you're doing dynamically changing panels (i.e. adding/removing components on the fly) you should use the netbeans designer, so all the Swing elements are in one place.

-- EDIT --
And you can only put one component into BorderLayout.CENTER per panel. If you put more than one element into the same position of a panel, what gets painted is not well defined, i.e. it may be either of the elements (or both).

Stroboskop
+1  A: 

You need to set the layout of the panel before you add the button with BorderLayout.CENTER. Also, you must remove and add the first button again and invoke the revalidate() method on the panel.

Change your addSecond() method as below and it should work.

private void addSecond() {
    JButton secondButton = new JButton("Button - 2");

    this.setLayout(new BorderLayout());
    remove(firstButton);
    add(firstButton, BorderLayout.NORTH);
    add(secondButton, BorderLayout.CENTER);

    revalidate();
}
Chandru
I didn't know I had to completely recreate the layout instance, I'll change the code. Thank you.
mizipzor