【问题标题】:Vaadin - Iterate over components in a layoutVaadin - 迭代布局中的组件
【发布时间】:2013-05-11 10:50:45
【问题描述】:

我正在使用 Vaadin 7 开发一个项目。我需要解析 Layout 中的所有组件并找到我需要的组件。

以上是我的布局的图示。

我在蓝色垂直布局内动态创建绿色垂直布局。因为我是动态创建它们的,所以我不能为那些动态创建的东西提供任何实例。但是,我对所有组件都有唯一的 ID。

现在我需要使用 Id 找到一个 Combobox。我不知道如何从蓝色垂直布局解析到组合框。

我所拥有的只是一个蓝色垂直布局的实例和组合框的 ID。 而且,如果需要,我也可以拥有绿色和红色布局的 ID。

我需要这样的东西,但是卡住了..

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

【问题讨论】:

  • 将以后需要的所有组件放入hashset并使用ID作为键是一个想法吗?

标签: layout dynamic iterator components vaadin


【解决方案1】:

你必须递归地检查组件。

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");

希望对你有帮助

【讨论】:

    【解决方案2】:

    虽然使用HasComponents.iterator() 仍然是可能的com.vaadin.ui.AbstractComponentContainer 实现java.lang.Iterable&lt;Component&gt;,这使得迭代更加舒适:

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

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      相关资源
      最近更新 更多