java 在 JPanel 中动态添加组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3599474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:35:40  来源:igfitidea点击:

adding components dynamically in a JPanel

javaswing

提问by Lalchand

how can i add components dynamically in a jpanel? I am having add button when i click the button the components should be added to the JPanel.

如何在 jpanel 中动态添加组件?当我单击应该将组件添加到 JPanel 的按钮时,我正在添加按钮。

my question is that adding a textfield and button to jpanel when i click on the add button the user can click on the add button any number of times according to that i have to add them to the jpanel. i have added to scrollerpane to my jpanel,and jpanel layout manager is set to null.

我的问题是当我点击添加按钮时向 jpanel 添加一个文本字段和按钮,用户可以根据我必须将它们添加到 jpanel 中任意次数地点击添加按钮。我已将 scrollerpane 添加到我的 jpanel,并且 jpanel 布局管理器设置为 null。

回答by crusam

Just as you always do, except that you have to call:

和往常一样,除了您必须调用:

panel.revalidate();

when you are done, since the container is already realized.

完成后,因为容器已经实现。

回答by miku

Use an ActionListener, you can use an anonymous class like this:

使用ActionListener,您可以使用这样的匿名类:

JPanel myJPanel = new JPanel();

...

b = new Button("Add Component");
b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JLabel someLabel = new JLabel("Some new Label");
        myJPanel.add(someLabel);
        myJPanel.revalidate();
    }
});