简体   繁体   中英

GWT getElementbyId to equivalent widget / Panel

I'm trying to build a dynamic web app in GWT, when widgets are added to the screen I remember their 'name' by setting the Widget.setId, when I want to replace part of the page, I can find the element in question via DOM.getElementById('name'), and its parent using DOM.getParentElement(), and then remove its children.

Now I have a com.google.gwt.dom.client.Element object (the parent). What I want to do is turn this back into a GWT object - in fact it'll be something derived from Panel, so I can add additional Widgets.

How do I go from the Element object back to a Panel object ?

I totally accept I could be going about this the wrong way, in which case is there a better way?

I think your approach to remove widgets from the DOM using DOM.getElementById('name') is not the proper one.

On your case (I am just figuring out what you do), I would keep Java Objects references instead of accessing to them using the DOM.

For instance:

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));
}

UPDATE

Based on your comments, I would propose the following solution. I suppose that you are storing widgets on HorizontalPanel , just apply this solution to your concrete case. I propose to use customized class which inherits from HorizontalPanel and add a Map there to store relationship between names and widgets.

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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM