2012-12-05 119 views
5

有沒有一種方法可以在SWT-Widgets上自動生成ID以便UI-Tests可以引用它們?我知道我可以使用seData手動設置一個id,但我想以某種通用的方式爲現有的應用程序實現此功能。在SWT-Widgets上自動生成ID

回答

8

您可以使用Display.getCurrent().getShells();Widget.setData();以遞歸方式爲您的應用程序中的所有shell分配ID。

設置標識

Shell []shells = Display.getCurrent().getShells(); 

for(Shell obj : shells) { 
    setIds(obj); 
} 

你有方法Display.getCurrent().getShells();訪問所有活動(未配置)炮彈在你的應用程序。您可以遍歷每個Shell的所有孩子,並使用方法Widget.setData();爲每個Control分配一個ID。

private Integer count = 0; 

private void setIds(Composite c) { 
    Control[] children = c.getChildren(); 
    for(int j = 0 ; j < children.length; j++) { 
     if(children[j] instanceof Composite) { 
      setIds((Composite) children[j]); 
     } else { 
      children[j].setData(count); 
      System.out.println(children[j].toString()); 
      System.out.println(" '-> ID: " + children[j].getData()); 
      ++count; 
     } 
    } 
} 

如果ControlComposite它可能有複合的內部控制,這是我用在我的例子遞歸解決方案的原因。


通過ID

尋找控制現在,如果你想找到一個控制在你的貝殼之一,我會建議一個類似的,遞歸的方法:

public Control findControlById(Integer id) { 
    Shell[] shells = Display.getCurrent().getShells(); 

    for(Shell e : shells) { 
     Control foundControl = findControl(e, id); 
     if(foundControl != null) { 
      return foundControl; 
     } 
    } 
    return null; 
} 

private Control findControl(Composite c, Integer id) { 
    Control[] children = c.getChildren(); 
    for(Control e : children) { 
     if(e instanceof Composite) { 
      Control found = findControl((Composite) e, id); 
      if(found != null) { 
       return found; 
      } 
     } else { 
      int value = id.intValue(); 
      int objValue = ((Integer)e.getData()).intValue(); 

      if(value == objValue) 
       return e; 
     } 
    } 
    return null; 
} 

隨着方法findControlById()你可以很容易地找到它的ID爲Control

Control foundControl = findControlById(12); 
    System.out.println(foundControl.toString()); 

鏈接