开发者

Check whether a JPanel contains a JButton

开发者 https://www.devze.com 2023-04-02 18:10 出处:网络
I have added a button to a JPanel. I want to remove the button if the JPanel contains the button.Is ther开发者_如何学运维e any way to check whether the JPanel contains the button?If you have a referen

I have added a button to a JPanel. I want to remove the button if the JPanel contains the button. Is ther开发者_如何学运维e any way to check whether the JPanel contains the button?


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).

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


Is checking necessary? If not, then just remove the JButton without checking. Nothing will happen if it is not contained by the JPanel.


If you have a reference to the button:

List<Component> componentList = Arrays.asList(panel.getComponents());
if (!componentList.contains(button)) {
  panel.add(button);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号