Reputation: 23
I have a JMenuItem called newMI, in a class that extends JFrame. I want to add Swing components to my JFrame when I click the JMenuItem. For testing purposes, I am trying to add a JPanel and setting the background color of the JPanel to red.
Here is my ActionListener:
newMI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JPanel p = new JPanel();
p.setBackground(Color.red);
add(p);
}
}
However this isn't working. I can change the background color of the JPanel if I added it to the JFrame during the initialization of the other Swing components. But I can't add Swing components to the JFrame directly inside of an ActionListener. Can somebody please help?
Many thanks.
Upvotes: 2
Views: 3950
Reputation: 324118
When you dynamically add/remove components from a visible GUI then you need to do:
panel.add(...);
panel.revalidate();
panel.repaint();
If you need more help then post your SSCCE that demonstrates the problem.
Upvotes: 8
Reputation: 2414
you need to re-layout your component -- your new panel has been added, but has a size of 0x0 px. Call layout(true)
on your component after adding the panel.
In case you don't have a layout manager in your component, you must set the position and size of the added panel manually after adding it to your component.
Upvotes: 2