问题描述
在 HTML 中,有类似 document.getElementById("button1");
In HTML, there is something like document.getElementById("button1");
我希望在我的 SWT 应用程序中发生这样的事情.
I would like something of this sort to happen in my SWT application.
假设我在运行时使用 new Button(shell, SWT.PUSH)
创建了一个 SWT 小部件有没有什么地方可以使用类似于 getElementById(...)
的东西来获取(引用)这个对象?
Say I created an SWT widget on the run with new Button(shell, SWT.PUSH)
Is there anywhere I can get(reference) this object with something similar to getElementById(...)
?
我正在考虑创建一个 HashMap
类型,其中 String 放置对象的 id(小部件),然后我将调用 hashMap.getKey(id)
它将返回对对象(小部件)的引用.
I am thinking of creating a HashMap<String, Object>
type, where String places the id of the object(Widget) and then I will call hashMap.getKey(id)
which will return me a reference to the object(Widget).
推荐答案
您可以使用这样的方法递归检查组合的所有子项,并使用 Widget.getData()/setData() 设置一个 id:
You can recursively check all the children of a composite with a method like this one, and use Widget.getData()/setData() to set an id:
public <T extends Control> T findChild(Composite parent, String id) {
Control found = null;
Control[] children = parent.getChildren();
for (int i = 0; i < children .length && found == null; i++) {
Control child = children[i];
if (id.equals(child.getData(ID)) {
found = child;
} else if (child instanceof Composite) {
found = findChild((Composite) child, id);
}
}
return (T) found ;
}
这篇关于HTML“getElementByID"SWT 小部件的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!