简体   繁体   English

如何在ActionListener中添加Swing组件?

[英]How to add Swing components in an ActionListener?

I have a JMenuItem called newMI, in a class that extends JFrame. 我在一个扩展JFrame的类中有一个名为newMI的JMenuItem。 I want to add Swing components to my JFrame when I click the JMenuItem. 我想在单击JMenuItem时将Swing组件添加到我的JFrame中。 For testing purposes, I am trying to add a JPanel and setting the background color of the JPanel to red. 出于测试目的,我尝试添加JPanel并将JPanel的背景颜色设置为红色。

Here is my ActionListener: 这是我的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. 如果我在其他Swing组件的初始化期间将它添加到JFrame,我可以更改JPanel的背景颜色。 But I can't add Swing components to the JFrame directly inside of an ActionListener. 但我无法直接在ActionListener内部将Swing组件添加到JFrame。 Can somebody please help? 有人可以帮忙吗?

Many thanks. 非常感谢。

When you dynamically add/remove components from a visible GUI then you need to do: 当您从可见的GUI动态添加/删除组件时,您需要执行以下操作:

panel.add(...);
panel.revalidate();
panel.repaint();

If you need more help then post your SSCCE that demonstrates the problem. 如果您需要更多帮助,请发布证明问题的SSCCE

you need to re-layout your component -- your new panel has been added, but has a size of 0x0 px. 您需要重新布局组件 - 您的新面板已添加,但大小为0x0像素。 Call layout(true) on your component after adding the panel. 添加面板后,在组件上调用layout(true)

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. 如果组件中没有布局管理器,则必须在将添加的面板添加到组件后手动设置其位置和大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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