在SWT-Widgets上自动生成ID
有没有办法在SWT-Widgets上自动生成ID,以便UI-Tests可以引用它们? 我知道我可以使用seData手动设置id,但我想以一种通用的方式为现有应用程序实现此function。
您可以使用Display.getCurrent().getShells();
以递归方式为应用程序中的所有shell分配Display.getCurrent().getShells();
和Widget.setData();
。
设置ID
Shell []shells = Display.getCurrent().getShells(); for(Shell obj : shells) { setIds(obj); }
您可以使用Display.getCurrent().getShells();
方法访问应用程序中的所有活动(未处置)Shell Display.getCurrent().getShells();
。 您可以遍历每个Shell
所有子项,并使用方法Widget.setData();
为每个Control
分配一个ID Widget.setData();
。
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; } } }
如果Control
是Composite
它可能在复合内部有控件,这就是我在我的例子中使用递归解决方案的原因。
按ID查找控件
现在,如果你想在你的一个shell中找到一个Control,我建议采用类似的递归方法:
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());
链接
- SWT API:小部件
- SWT API:显示