2013-05-16 39 views
8

我正在研究Vaadin 7中的項目。在此我需要解析佈局中的所有組件,並找到我需要的組件。Vaadin - 遍歷佈局中的組件

enter image description here

以上是我的佈局的圖示。

我正在動態創建藍色垂直佈局內的綠色彩色垂直佈局。由於我正在動態創建它們,因此我無法爲這些動態創建的事件創建任何實例。但是,我擁有所有組件的唯一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 
     } 
    } 
+0

難道是把所有的成分你的想法將需要稍後在哈希集並使用ID作爲關鍵? –

回答

11

你必須遞歸查詢組件。

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

希望它可以幫助

+0

超棒的男人。它完美無瑕。 – Gugan

0

雖然使用HasComponents.iterator()仍然是可能的com.vaadin.ui.AbstractComponentContainer實現java.lang.Iterable<Component>,這使得迭代有點更舒適:

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