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?
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 therevalidate()method on the panel.Change your addSecond() method as below and it should work.