Vaadin - Iterate over components in a layout


The above is the pictorial representation of my layout.

I’m dynamically creating the green coloured Vertical layout inside blue coloured Vertical layout. Since I’m creating them dynamically, I can’t have any instance for those dynamically created things. But, I have unique ID’s for all the components.

Now I need to find a Combobox using the Id. I donno how to parse in to the combobox from the Blue coloured vertical layout.

All I have is an instance of the blue coloured vertical layout and Id’s for combobox. And, I can have ID’s for green and red layouts too if needed.

I need something like this, But stuck…

Iterator<Component> iterate = blueMainLayout.iterator();
Combobox cb;
while (iterate.hasNext()) {
Component c = (Component) iterate.next();
cb = (Combobox) blueMainLayout.....;
        if (cb.getId().equals(something.getId())) {
            // do my job
        }
    }

You need to recursively walk the component tree. This should do it:

Component findComponentWithId(HasComponents root, String id) {
    for(Component child : root) {
        if(id.equals(child.getId())) {
            // found it!
            return child;
        } else if(child instanceof HasComponents) {
            // recursively go through all children that themselves have children
            return findComponentWithId((HasComponents) child, id);
        }
    }
    // none was found
    return null;
}

[/code]Usage:[code]

Component c = findComponentWithId(blueMainLayout, something.getId());
if(c instanceof ComboBox) {
     // do my job
}

Thank you Johan, It worked for me.

Hi
I use this answer to solve my problem.
But I found the new problem is
When the child components was in HorizontalSplitPanel,
Like :
HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
Table a=new Table();
a.setId(“A”);

    Table b=new Table();
    b.setId("B");
    splitPanel.addComponents(a,b);

can not find the table “B” ?
just don’t know why?
If I disable to add the table “A” to HorizontalSplitPanel then the table “B” found !

Someone help me !

Solve it !
Change HasComponents to ComponentContainer
in Johannes Dahlström 's method.

No ,I am wrong !
It doesn’t matter about ComponentContainer or HasComponents.
There are bug in answer method.

Component findComponentWithId(HasComponents root, String id) {
for(Component child : root) {
if(id.equals(child.getId())) {
// found it!
return child;
} else if(child instanceof HasComponents) {
// recursively go through all children that themselves have children

return findComponentWithId((HasComponents) child, id);
[color=#FF0000]
[size=5]
[b]
<–bug here(cause short cut)

–>change to:
[/b]
[/size]
[/color]




Component ret= findComponentWithId((HasComponents) child, id);
if(ret!=null)return ret;



    }
}
// none was found
return null;

}

Great…excactly what I needed…thank you!

Great…excactly what I needed…thank you!