GWT Widget.addHandler

Peter picture Peter · Jun 30, 2011 · Viewed 24.5k times · Source

I am trying to utilize Widget.addHandler(). However, the handler never gets called. Below is my sample code. What do I need to change to fix this?

My Handler Implementation:

public class CustomMouseMoveHandler
  extends GwtEvent.Type<MouseMoveHandler>
  implements MouseMoveHandler
{
  @Override
  public void onMouseMove(MouseMoveEvent event) {
    System.out.println("----> onMouseMove.");
  }
}

My EntryPoint.OnModuleLoad():

ContentPanel cp = new ContentPanel();
cp.setHeaderVisible(false);
cp.setHeight(com.google.gwt.user.client.Window.getClientHeight());

CustomMouseMoveHandler handler = new CustomMouseMoveHandler();
cp.addHandler(handler, handler);

RootPanel.get().add(cp);

///// Added on 7/1/2011.

The following complete GWT simple code does not work either (with Jason's hint applied). Please help me out. Thanks

 package tut.client;

 import com.google.gwt.core.client.EntryPoint;
 import com.google.gwt.event.dom.client.MouseMoveEvent;
 import com.google.gwt.event.dom.client.MouseMoveHandler;
 import com.google.gwt.user.client.ui.RootPanel;
 import com.google.gwt.user.client.ui.TextArea;

  /**
  * Entry point classes define <code>onModuleLoad()</code>.
  */
    public class GwtHandler implements EntryPoint, MouseMoveHandler {

        /**
         * This is the entry point method.
         */
        public void onModuleLoad() {
           TextArea comp = new TextArea();

           comp.setSize("200px", "200px");
           comp.setText("Testing Text");        

           comp.addHandler(this, MouseMoveEvent.getType());

           RootPanel.get().add(comp);
        }

       @Override
       public void onMouseMove(MouseMoveEvent event) {
           com.google.gwt.user.client.Window.alert("onMouseMove");
       }
}

Answer

Jason Terk picture Jason Terk · Jun 30, 2011

GwtEvent.Type is used to dispatch events based on an event specific and unique object (object equality - == - is used to match event types). Passing your CustomMouseMoveHandler as the Type to addHandler indicates an event type other than that used for MouseMoveEvents (Indeed in this case every CustomMouseMoveHandler would be assigned to a different event Type since each object is different).

Instead of extending GwtEvent.Type<MouseMoveHandler> in your handler you need to get the event Type from MouseMoveEvent itself (using the static getType() method).

Don't extend GwtEvent.Type in your CustomMouseMoveHandler:

public class CustomMouseMoveHandler
  implements MouseMoveHandler
{
  ...
}

And to add the handler:

cp.addDomHandler(handler, MouseMoveEvent.getType());