Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Fast Way to Determine Whether A Componet is Found In JPanel

Tags:

java

swing

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?

like image 652
Cheok Yan Cheng Avatar asked May 13 '09 18:05

Cheok Yan Cheng


2 Answers

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.

like image 108
kdgregory Avatar answered Oct 19 '22 23:10

kdgregory


you can use

jPanel.isAncestorOf(component)

for recursive search

like image 26
Alex Avatar answered Oct 19 '22 23:10

Alex