【问题标题】:HTML "getElementByID" implementation for SWT widgetSWT 小部件的 HTML“getElementByID”实现
【发布时间】:2012-07-31 07:50:16
【问题描述】:

在 HTML 中,有类似document.getElementById("button1");

我希望在我的 SWT 应用程序中发生这种事情。

假设我在运行时使用new Button(shell, SWT.PUSH) 创建了一个 SWT 小部件 有没有什么地方可以用类似于getElementById(...) 的东西获取(引用)这个对象?

我正在考虑创建一个HashMap<String, Object> 类型,其中String 放置对象(Widget) 的ID,然后我将调用hashMap.getKey(id),它将返回一个对对象(Widget) 的引用。

【问题讨论】:

    标签: java swt


    【解决方案1】:

    不,SWT 小部件没有 ID 或类似的东西。当然,您可以使用地图手动完成,如您所说。

    【讨论】:

      【解决方案2】:

      有多种可能性来实现这样的功能,而无需付出任何努力。作为示例实现,您可以使用 SWTBot(SWT 的 GUI 测试 API),它有多种方法可以通过给定的 id “查找”小部件。

      下载 SWTBot 源代码(请参阅 http://wiki.eclipse.org/SWTBot/Contributing#Getting_the_source)并查看 org.eclipse.swtbot.swt.finder.SWTBot.buttonWithId(String, String, int) 的示例。如果您浏览实现,您将了解如何实现它...

      【讨论】:

        【解决方案3】:

        您可以使用类似这样的方法递归检查组合的所有子项,并使用Widget.getData()/setData() 设置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 ;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-07-05
          • 2018-08-22
          • 2011-10-21
          • 2010-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-01
          • 1970-01-01
          相关资源
          最近更新 更多