Gugan Mohan
Gugan Mohan

Reputation: 1645

Vaadin - Iterate over components in a layout

I'm working on a project in Vaadin 7. In that I need to parse over all the components in a Layout and find a component I need.

enter image description here

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
        }
    }

Upvotes: 8

Views: 10418

Answers (2)

Gerold Broser
Gerold Broser

Reputation: 14772

Though using HasComponents.iterator() is still possible com.vaadin.ui.AbstractComponentContainer implements java.lang.Iterable<Component>, which makes the iteration a bit more comfortable:

  ...
  for ( Component c : layout ) {
    if ( id.equals( c.getId() ) ) {
      return c;
    }
  }
  ...  

Upvotes: 2

Serge Farny
Serge Farny

Reputation: 932

You have to check component recursively.

class FindComponent {
    public Component findById(HasComponents root, String id) {
        System.out.println("findById called on " + root);

        Iterator<Component> iterate = root.iterator();
        while (iterate.hasNext()) {
            Component c = iterate.next();
            if (id.equals(c.getId())) {
                return c;
            }
            if (c instanceof HasComponents) {
                Component cc = findById((HasComponents) c, id);
                if (cc != null)
                    return cc;
            }
        }

        return null;
    }
}

FindComponent fc = new FindComponent();
Component myComponent = fc.findById(blueMainLayout, "azerty");

Hope it helps

Upvotes: 11

Related Questions