简体   繁体   中英

How to add Swing components in an ActionListener?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM