在SWT-Widgets上自动生成ID [英] Automatically generate IDs on SWT-Widgets
问题描述
有没有办法在SWT-Widgets上自动生成ID,因此UI-Tests可以引用它们?我知道我可以使用seData手动设置id,但我想以一种通用的方式为现有应用程序实现此功能。
Is there a way to automatically generate IDs on SWT-Widgets so UI-Tests can reference them? I know i can manually set an id using seData but I want to implement this feature for an existing application in a somewhat generic fashion.
推荐答案
您可以使用 Display.getCurrent()。getShells();
和 Widget.setData()以递归方式为应用程序中的所有shell分配ID ;
。
设置ID
Shell []shells = Display.getCurrent().getShells();
for(Shell obj : shells) {
setIds(obj);
}
您可以访问应用程序中的所有活动(未处置)Shell方法 Display.getCurrent()。getShells();
。您可以遍历每个 Shell
的所有子项,并使用方法 Control
分配一个ID > Widget.setData(); 。
You have access to all the active (not disposed) Shells in your application with the method Display.getCurrent().getShells();
. You can loop through all children of each Shell
and assign an ID to each Control
with the method 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
它可能在复合内部有控件,这就是我在我的例子中使用递归解决方案的原因。
If the Control
is a Composite
it may have controls inside the composite, that's the reason I have used a recursive solution in my example.
按ID查找控件
现在,如果你想在你的一个shell中找到一个Control,我会建议一个类似的,递归的方法:
Now, if you like to find a Control in one of your shells I would suggest a similar, recursive, approach:
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
。
With the method findControlById()
you can easily find a Control
by it's ID.
Control foundControl = findControlById(12);
System.out.println(foundControl.toString());
链接
- SWT API: Widget
- SWT API: Display
这篇关于在SWT-Widgets上自动生成ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!