Check if JPanel contains JButton

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

+4
source share
3 answers

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

Alternatively, do as @kleopatra suggested, and call getComponents () on the JPanel instance and iterate through the array, looking for everything that instanceof JButton .

+8
source

Is verification required? If not, just uninstall JButton without checking. Nothing will happen if it is not contained in JPanel .

+7
source

If you have a link to a button:

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

All Articles