从 JPanel 动态删除组件
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有趣的是,我遇到了同样的问题,我很惊讶人们对另一个答案投了赞成票,因为他明确询问的是动态创建的组件,而不是已经在可获得的变量名称下创建的组件,而是匿名创建的对象。
答案很简单。使用
getComponents() 进行迭代通过添加到 JPanel 的组件数组。找到您要删除的组件类型,例如使用 instanceof 。在我的示例中,我删除了添加到 JPanel 的所有 JCheckBox。
确保重新验证并重新绘制面板,否则更改将不会显示
组件来自 java.awt.Component。
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.
使用
Container.remove(Component)
方法,您可以从容器中删除任何组件。例如:Using the method
Container.remove(Component)
, you can remove any component from the container. For example: