A quick way to determine if a component is found in JPanel

Can I find out how to determine if a component is found in JPanel?

boolean isThisComponentFoundInJPanel(Component c)
{
    Component[] components = jPanel.getComponents();
    for (Component component : components) {
        if (c== component) {
                return true;
        }
    }
    return false;
}

Using a loop is inefficient. Is there a better way?

+5
source share
3 answers
if (c.getParent() == jPanel)

The call is recursive if you don't need a direct parent-child relationship (which probably takes place in a well-designed panel).

... although in a well-designed panel, it is very doubtful why you need to know if the component is contained in the panel.

+11
source

you can use

jPanel.isAncestorOf(component)

for recursive search

+4
source

.

, , . GUI, , .

Probably the best way to write code is to use existing routines. Although there is some overhead, they are most likely already compiled (possibly faster) and less code.

boolean isComponentInPanel(Component component) {
    return
        java.util.Arrays.asList(panel.getComponents())
            .contains(component);
}

(Or use kdgregory's answer.)

+3
source

All Articles