Java – recursively find the object and return null after finding it

I have created a recursive method to find jcomponents by name This method looks for the correct component, but it returns null I guess I didn't handle the return of the component and return null correctly How can I work normally?

Editor: instead, I understand from the comments below But it does not return components

public Component findComponent(String str,Component tt){   

    for (Component c : ((Container) tt).getComponents()) {
        System.out.println("name: " + c.getName());
        if(c.getName().equals(str)){
            System.out.println("Found it! " + c.getName());
            return c;
        } else {
            return findComponent(str,c);
        }
    }   
    return null;
}

This will stop immediately One component has no component, so I guess it will stop immediately and return null?

If I delete the return value from findcomponent (STR, c); The console gives:

name: titel
name: l
name: jpj
name: jtx
name: jpath
Found it! jpath
name: knapper
name: k1
name: n1
name: k2
name: n2
name: k3
name: n3
name: jpp
name: text
name: jpe
name: ta

Title is a title that does not contain any components Is this a new question?

Solution

Your other blocks should be:

else {
  Component sub = findComponent(str,c);
  if (sub != null) return sub;
}

Otherwise, you will only check your first component, only its first sub component, and only the first sub component, and so on

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>