Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT: How do I get a reference to a button from the RootPanel?

Tags:

gwt

I'm using GWT 2.4. In my onModuleLoad method, given a string id, how do I get a reference to an existing button on the page from the RootPanel object? I'm trying this

public void onModuleLoad() {
    ...
    final Button submitButton = (Button) RootPanel.get("submit");

but getting the compile error, "Cannot cast from RootPanel to Button".

Edit:

I thought using an iterator would heal the pain, but no dice. Here is the default HTML loaded (notice the button with id="submit") ...

<div>

    <form name="f">

        File name: <input type="text" size="25" id="filename" name="filename"

            value="" /> <input type="button" id="submit" name="submit"

            value="Submit" /> <input type="hidden" name="curId" id="curId"

            value="" />

    </form>

</div>

<div id="content"></div>

but this code in onModuleLoad causes a NullPointerException (because the submitButton id can't be found) ...

public void onModuleLoad() {

    final Button submitButton = (Button) getWidgetById("submit");
    submitButton.addStyleName("submitButton");
    ...

private Widget getWidgetById(final String id) {
    Widget eltToFind = null;
    final Iterator<Widget> iter = RootPanel.get().iterator();
    while (iter.hasNext()) {
        final Widget widget = iter.next();
        final Element elt = widget.getElement();
        if (elt.getId() != null && elt.getId().equals(id)) {
            eltToFind = widget;
            break;
        } // if
    } // while
    return eltToFind;
}

Thanks, - Dave

like image 362
Dave Avatar asked Dec 04 '22 19:12

Dave


2 Answers

You can get your input element using Document.get().getElementById("submit").<InputElement>cast(), but you won't be able to get a Button widget out of it.

If you change your code to read <button type="button" id="submit" name="submit" value="Submit"> instead of <input> (the type=button part is technically not needed, but some browsers will treat it like a type=submit if you don't), then you can use Button.wrap():

Button button = Button.wrap(Document.get().getElementById("submit"));
like image 100
Thomas Broyer Avatar answered Dec 07 '22 09:12

Thomas Broyer


Some of GWT widgets have static method wrap() which allows to convert DOM elements to widget instances.

Button submit = Button.wrap(DOM.getElementById("submit"));

like image 22
cardamo Avatar answered Dec 07 '22 07:12

cardamo