tags:

views:

164

answers:

3

May I know how can I determine whether 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 loop is not efficient. Is there any better way?

+5  A: 
if (c.getParent() == jPanel)

Call recursively if you don't want immediate parent-child relationships (which is probably the case in a well-designed panel).

... although in a well-designed panel, it's very questionable why you'd need to know whether a component is contained in the panel.

kdgregory
+1 for "... although in a well-designed panel, it's very questionable why you'd need to know whether a component is contained in the panel."
Alex B
Is a dynamic panel a poorly designed panel?
There are no one rule that fit for all. Use common sense. Dynamic panel is good and my users is happy about it, and dynamic panel need to discover parent/ child dynamically during run-time. As along as my users is happy, it is nothing to be questionable when I need to know whether a component is contained in the panel.
Yan Cheng CHEOK
+2  A: 

Performance of this operation is highly unlikely to be a bottleneck.

Looking through the contents of a container probably indicates bad design. Tell the GUI what to do, don't interrogate its state.

Probably a better way to write the code is to use existing routines. Whilst there is some overhead, they are more likely to be already compiled (therefore possibly faster) and are less code.

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

(Or use kdgregory's answer.)

Tom Hawtin - tackline
+1  A: 

you can use

jPanel.isAncestorOf(component)

for recursive search

Alex