从 JPanel 动态删除组件

发布于 2024-11-30 06:34:33 字数 106 浏览 0 评论 0原文

我在 JPanel 中动态添加和删除组件。 添加和删​​除功能工作正常,但是当我删除组件时,它会删除最后一个组件而不是要删除的组件。

我该如何解决这个问题?

I am adding and deleting components dynamically in a JPanel.
Adding and deleting functionality works fine but when I delete the component it deletes the last component rather than the component to be deleted.

How can I solve this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

书信已泛黄 2024-12-07 06:34:33

有趣的是,我遇到了同样的问题,我很惊讶人们对另一个答案投了赞成票,因为他明确询问的是动态创建的组件,而不是已经在可获得的变量名称下创建的组件,而是匿名创建的对象。

答案很简单。使用
getComponents() 进行迭代通过添加到 JPanel 的组件数组。找到您要删除的组件类型,例如使用 instanceof 。在我的示例中,我删除了添加到 JPanel 的所有 JCheckBox。

确保重新验证并重新绘制面板,否则更改将不会显示

组件来自 java.awt.Component。

//Get the components in the panel
Component[] componentList = panelName.getComponents();

//Loop through the components
for(Component c : componentList){

    //Find the components you want to remove
    if(c instanceof JCheckBox){

        //Remove it
        clientPanel.remove(c);
    }
}

//IMPORTANT
panelName.revalidate();
panelName.repaint();

Interestingly enough I am coming across the same issue and I am surprised people are upvoting the other answer, as he is clearly asking about dynamically created Components, not components already created under a variable name which is obtainable, instead of anonymously created objects.

The answer is pretty simple. Use
getComponents() to iterate through an array of components added to the JPanel. Find the kind of component you want to remove, using instanceof for example. In my example, I remove any JCheckBoxes added to my JPanel.

Make sure to revalidate and repaint your panel, otherwise changes will not appear

Component is from java.awt.Component.

//Get the components in the panel
Component[] componentList = panelName.getComponents();

//Loop through the components
for(Component c : componentList){

    //Find the components you want to remove
    if(c instanceof JCheckBox){

        //Remove it
        clientPanel.remove(c);
    }
}

//IMPORTANT
panelName.revalidate();
panelName.repaint();
小梨窩很甜 2024-12-07 06:34:33

使用Container.remove(Component)方法,您可以从容器中删除任何组件。例如:

JPanel j = new JPanel();

JButton btn1 = new JButton();

JButton btn2 = new JButton();

j.add(btn1);

j.add(btn2);

j.remove(btn1);

Using the method Container.remove(Component), you can remove any component from the container. For example:

JPanel j = new JPanel();

JButton btn1 = new JButton();

JButton btn2 = new JButton();

j.add(btn1);

j.add(btn2);

j.remove(btn1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文