Search code examples
gwtcomponentscustom-componentsmartgit

GWT: retrieve Components from FormPanel/VerticalPanel which are added dynamically


I am creating a web page using GWT 2.5.0, in this I used lots of composite component. And the web page is developed based on XML .

So here we parse the XML and according to each element add componnet to a VerticalPanel and finally add it to a FormPanel and then return it to add to RootPanel. Beside the Component corresponds to XML I add a Button, call it submit button, on its click event I want to get the values of every component in that form. To clear what my idea is , below is the pseudo code of my work:

public FormPanel createFormWithComponents(){

    FormPanel fp = new FormPanel();
    vp = new VerticalPanel();
    //these are creatred based on the xml
    ABC coutn = new ABC (null,"pressure count",true);
    PI propotion =  new PI(12.5,"HR percentage");

    vp.add(coutn);
    vp.add(propotion);
    //a common button to every form created here
    Button submit = new Button("submit");
    vp.add(submit);
    submit.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {

UPDATED

                String values = "";
                Iterator<Widget> vPanelWidgets =  vp.iterator();
                while (vPanelWidgets.hasNext()){
                    Widget childWidget = vPanelWidgets.next();
                    if(childWidget instanceof ABC){
                        ABC xx = (ABC )childWidget;
                        values = String.valueOf(xx.getMagnitude());
                    }
                }
                Window.alert(values);
            }
        });

        fp.add(vp);
        return fp;
    }

Any insight would be appreciated. UPDATED: Here am comparing each of child widget component with one of my Composite component , do i have to do like this comparing to all Composite component? I there any kind of simple or optimized way to do it? I want good solution for doing this process as there are so many composite component over there:

if(childWidget instanceof ABC ){
    ABC xx = (ABC )childWidget;
    values = String.valueOf(xx.getMagnitude());
}

Solution

  • You could make all you Composite components implement an interface having a single getValue() method:

    public interface HasValue {
        public String getValue();
    }
    

    Then you can easilly extract the value of all widgets implementing that interface:

        while (vPanelWidgets.hasNext()){
            Widget childWidget = vPanelWidgets.next();
            if(childWidget instanceof HasValue){
                HasValue xx = (HasValue) childWidget;
                values = xx.getValue();
            }
        }
    

    If you need to return values other than strings, you could use generics. Take a look at GWT's com.google.gwt.user.client.ui.HasValue for an example of that (you could also use that interface instead of creating your own).