Tuesday, June 30, 2009

Tips on converting GWT Listeners to new Handlers

These tips all depend on using Eclipse.

Start with all the ClickListeners and do them all at once. Use Eclipse "Java Search": Search String = ClickListener, Search For = Type, Limit To = References.

For simple click situations, copy these lines:

.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{

and paste them in to replace every instance of

.addClickListener(new ClickListener() {
public void onClick(Widget sender)
{

Here's an extra tip: Instead of pasting the above code from here, paste it once into one of your classes. Once you get it valid there, copy that and paste it in to replace all your listeners. When you copy and paste this way, eclipse automatically pulls in the imports for you as well.

If the sender parameter had been used, replace references to it with event.getSource(). You will probably have to cast it.

For other situations, make heavy use of auto-complete (CTRL-SPACE). For example

myObject.addCl<CTRL-SPACE><ENTER> -> myObject.addClickHandler()

myObject.addClickHandler(new <CTRL-SPACE><ENTER>) -> myObject.addClickHandler(new ClickHander)

myObject.addClickHandler(new ClickHander() {<ENTER>) ->

myObject.addClickHandler(new ClickHander() {

})

myObject.addClickHandler(new ClickHander() {
<CTRL-SPACE><ENTER>
})

->

myObject.addClickHandler(new ClickHander() {
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub

}
})

Final tip: Put your cursor at the end of a listener class name (ex: new ClickListener|()) and press <CTRL-SPACE>. This will bring up the class along with other suggestions in a list. But it will also show the Java Doc for that class, which will tell you what handler(s) you should use instead. The same works for methods like addClickListener().