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?
Asked
Active
Viewed 8,194 times
4

Brian
- 14,610
- 7
- 35
- 43

JavaLearner
- 41
- 1
- 2
-
2what's wrong with looping through the panel's children? – kleopatra Sep 05 '11 at 12:02
3 Answers
10
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
.

Andrew Thompson
- 168,117
- 40
- 217
- 433
7
Is checking necessary? If not, then just remove the JButton
without checking. Nothing will happen if it is not contained by the JPanel
.

Mohayemin
- 3,841
- 4
- 25
- 54
-
The question is: 'how can I check whether a JPanel contains a JButton?'. People that search for that question will be referred to this answer. This answer is good advice for the asker's particular purpose, but not an adequate answer to the general question. – Maarten Oct 14 '12 at 17:18
-
@Maarten: You are right. I answered the question description, not the title but people are usually interested about the title. I think [Andrew's Answer](http://stackoverflow.com/a/7318993/887149) bellow is good for that. – Mohayemin Oct 15 '12 at 03:08
1
If you have a reference to the button:
List<Component> componentList = Arrays.asList(panel.getComponents());
if (!componentList.contains(button)) {
panel.add(button);
}

ceklock
- 6,143
- 10
- 56
- 78