GWT getElementbyId到等效的小部件/面板

时间:2015-09-23 15:26:20

标签: java gwt

我正在尝试在GWT中构建一个动态Web应用程序,当窗口小部件添加到屏幕时我通过设置Widget.setId来记住它们的“名称”,当我想要替换部分页面时,我可以找到有问题的元素通过DOM.getElementById('name'),其父元素使用DOM.getParentElement(),然后删除它的子元素。

现在我有一个com.google.gwt.dom.client.Element对象(父对象)。我想要做的是将它转回GWT对象 - 实际上它将是从Panel派生的东西,所以我可以添加额外的小部件。

如何从Element对象返回Panel对象?

我完全接受我可能会以错误的方式解决这个问题,在哪种情况下有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我认为您使用 DOM.getElementById(' name')从DOM中删除小部件的方法不合适。

关于你的情况(我只是弄清楚你做了什么),我会保留Java Objects引用,而不是使用DOM访问它们。

例如:

HorizontalPanel panel = new HorizontalPanel();
Widget w = new Widget();
//We add the one widget to the panel
panel.add(w);
//One more widget added
w = new Widget();
panel.add(w);
//Now we remove all the widgets from the panel
for(int i = 0; i < panel.getWidgetCount(); i++){
    panel.remove(panel.getWidget(i));
}

<强>更新

根据您的意见,我建议采用以下解决方案。 我想您正在 Horizo​​ntalPanel 上存储小部件,只需将此解决方案应用于您的具体案例。 我建议使用继承自 Horizo​​ntalPanel 的自定义类,并在那里添加 Map 来存储名称和小部件之间的关系。

public class MyHorizontalPanel extends HorizontalPanel {

    private Map<String, Widget> widgetsMap;

    public MyHorizontalPanel(){
        super();
        widgetsMap = new HashMap<String, Widget>();
    }

    //We use Map to store the relationship between widget and name
    public void aadWidget(Widget w, String name){
        this.add(w);
        widgetsMap.put(name, w);
    }

    //When we want to delete and just have the name, we can search the key on the map.
    //It is important to remove all references to the widget (panel and map)
    public void removeWidget(String name){
        this.remove(widgetsMap.get(name));
        widgetsMap.remove(name);
    }

}