您可以使用以下命令为应用程序中的所有 shell 递归分配 ID:Display.getCurrent().getShells();
and Widget.setData();
.
设置 ID
Shell []shells = Display.getCurrent().getShells();
for(Shell obj : shells) {
setIds(obj);
}
您可以使用以下方法访问应用程序中所有活动的(未处置的)ShellDisplay.getCurrent().getShells();
。您可以循环遍历每个的所有子项Shell
并为每一个分配一个IDControl
用方法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;
}
}
}
If the Control
is a 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()
你可以很容易地找到一个Control
通过它的 ID。
Control foundControl = findControlById(12);
System.out.println(foundControl.toString());
Links