Handler on DOM elements in GWT

Mani picture Mani · May 14, 2013 · Viewed 18.7k times · Source

I want to add the handler on the buttonelement and i have implemented it as follow. Please help me in resolving the error in this code. I do not want to add handler directly on the button widget.

        Button button = new Button("Click");
        Element buttonElement = button.getElement();

        Event.setEventListener(buttonElement, new EventListener() {

            @Override
            public void onBrowserEvent(Event event) {

                String string = event.getType();

                if(string.equalsIgnoreCase("click")) {
                    System.out.println("CLICK");
                }
            }
        });

        Event.sinkEvents(buttonElement, Event.ONCLICK);

Answer

bNd picture bNd · May 14, 2013

Your code is correct, you might added widget after sink event. you have to add widget before sink event. just example:

Button  button=new Button("Click");
    Element buttonElement = button.getElement();
      RootPanel.get().add(button);
    Event.sinkEvents(buttonElement, Event.ONCLICK);
    Event.setEventListener(buttonElement, new EventListener() {

        @Override
        public void onBrowserEvent(Event event) {
            System.out.println("ok");
             if(Event.ONCLICK == event.getTypeInt()) {
                 Window.alert("ok");
                  System.out.println("CLICK");
             }

        }
    });