检查 JPanel 是否包含 JButton [英] Check whether a JPanel contains a JButton

查看:39
本文介绍了检查 JPanel 是否包含 JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向 JPanel 添加了一个按钮.如果 JPanel 包含按钮,我想删除该按钮.有没有办法检查JPanel是否包含按钮?

I have added a button to a JPanel. I want to remove the button if the JPanel contains the button. Is there any way to check whether the JPanel contains the button?

推荐答案

如果您有对 JButton 的引用,请调用 getParent().如果父元素为 null,则按钮不在面板(或任何容器)中.

If you have a reference to the JButton, call getParent(). If the parent is null, the button is not in the panel (or any container).

或者,按照@kleopatra 的建议进行操作并调用 JPanel 实例上使用 getComponents() 并迭代数组以查找任何属于 instanceof JButton 的内容.

Alternately, do as @kleopatra suggested and call getComponents() on the JPanel instance and iterate the array looking for anything that is an instanceof JButton.

这篇关于检查 JPanel 是否包含 JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆