views:

487

answers:

2

How do you add an event listener or handler to widgets in GWT 1.7?

I know there are some questions alreayd about this on SO but it seems they are outdated. For example (ignoring the fact that there is a :hover in CSS) how do I add a Hover listener to a FlexTable for example?

A: 

Starting in GWT 1.6 you use Handlers instead of Listeners. So for example, for hovering you would add a MouseOverHandler and MouseOutHandler. The FlexTable itself doesn't implement these interfaces so you'll probably want to implement it on the widgets contained in the FlexTable. For example,

myWidget.addMouseOverHandler(new MouseOverHandler(){
   void onMouseOver(MouseOverEvent event){
       doHovering();
    }
});

Similarly for adding a MouseOutHandler.

Joel
Do you know how I could handle that on the FlexTable? I found this link but I don't really understand how it works: http://www.java2s.com/Code/Java/GWT/TableMouseOverEvent.htm
drozzy
Also this shows how to implement this.. but I can't seem to cast the event to the elent that generated it: (Label)event.getEventTarget() doesnt work!http://code.google.com/webtoolkit/articles/dom_events_memory_leaks_and_you.html
drozzy
As for implementing this on a FlexTable, the FlexTable does not implement these interfaces. In the example you link to they are extending FlexTable as Table then adding the handlers to Table. You could something similar or perphaps just wrap a FlexTable with another widget that implements HasMouseOverHandler, for example a FocusPanel. As for how to find the target of the event, there is no getEventTarget method on the MouseOverEvent. The target of the vent is of course the widget that is implementing the MouseOverHandler.
Joel
A: 

If you want to add a MouseOverHandler to a FlexTable try this:

public class MyFlexTable extends FlexTable implements MouseOverHandler, HasMouseOverHandler {
    public MyFlexTable() {
        this.addMouseOverHandler(this);
    }

    public void onMouseOver(MouseOverEvent event) {
        //do something
    }
    public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
        return addDomHandler(handler, MouseOverEvent.getType());
    }
}
Chris Boesing
I didn't try it yet but i'll mark it accepted for now
drozzy