问题
In HTML, there is something like document.getElementById("button1");
I would like something of this sort to happen in my SWT application.
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(...)
?
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).
回答1:
No, SWT widgets don't have ids or anything similar. Of course, you can do it manually using a map, as you say.
回答2:
There are several possibilities to implement such a functionality without any big efforts. As an example-implementation you can use SWTBot (a GUI-Testing API for SWT) that has several methods to "find" Widgets by a given id.
Download the SWTBot Source-Code (see http://wiki.eclipse.org/SWTBot/Contributing#Getting_the_source) and take a look for example at org.eclipse.swtbot.swt.finder.SWTBot.buttonWithId(String, String, int)
If you navigate through the implementation you'll get an idea how this can be implemented...
回答3:
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 ;
}
来源:https://stackoverflow.com/questions/11735485/html-getelementbyid-implementation-for-swt-widget