Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClickHandler on an existing element in GWT

Tags:

gwt

I have an HTML document. In that document, there is an element (like button, div, a) with an ID. I know I can use:

Document.get().getElementById("id");

to find the required element in the HTML file. How can I add a Click handler to it? ClickHandlers only seem to be available on the Button class.

Thanks

like image 845
Honza Pokorny Avatar asked May 19 '10 21:05

Honza Pokorny


2 Answers

If you're trying to add a ClickHandler to a <button>, you can do that with Button.wrap().

For an <a> yo can use Anchor.wrap() (Anchors only have ClickListeners, not ClickHandlers...yet)

For a <div> you can use Label.wrap() (Labels are just <div>s).

like image 71
Jason Hall Avatar answered Nov 04 '22 11:11

Jason Hall


Suggestion : Try learning how to use UiBinder (added in GWT 2.0).

In your case, you could have done :

yourView.ui.xml

...
<g:Button ui:field="btnName" />
...

yourView.java

public class yourView extends Composite {
    interface MyUiBinder extends UiBinder<LayoutPanel, yourView> {}
    private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

    @UiField Button btnName;

    public yourView() {
        initWidget(uiBinder.createAndBindUi(this));
    }

    @UiHandler("btnName")
    void handleClick(ClickEvent e) {
        //Do whatever
    }
}

With "@UiHandler" you can add any handler the widget can support (implement Has****Handler). Adding other element to that structure is easy and FAST and you can add any kind of handler to it. @UiField create a variable containing the instance of the element that is manipulatable anywhere in your class.

like image 34
Zwik Avatar answered Nov 04 '22 13:11

Zwik