自定义ClickHandler类

时间:2013-04-05 08:18:33

标签: gwt interface onclick behavior

有没有办法在GWT中使用Clickhandler接口来构建自定义子类?我需要ClickHandlers,它应该在每次点击时做出反应。实现此行为不是实现的ClickHandler的问题,但如果不必将此代码段添加到每个ListBox元素,那将是很好的:

 boolean ingoreClick;
 lastSelection =  -1 ;
 listBox.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {

        if (!ignoreClick) {
            lastSelection = listBox.getSelectedIndex();
        }
        ignoreClick = !ignoreClick;     
    }
});

现在想象有listbox1,listbox2等等。

2 个答案:

答案 0 :(得分:1)

是的,因为Clickhandler是接口,您可以在自定义类中实现任何行为并在任何地方使用它。

  public class MyClickHancler implements ClickHandler {
    boolean first = false;
    String name;

    public MyClickHancler(String name) {
      this.name = name;
    }

    public void onClick(ClickEvent event) {
      if (first = !first) {
        System.out.println("First click on " + name);
      } else {
        System.out.println("Second click on " + name);
      }
    }
  }

  [...]

  widget1.addClickHandler(new MyClickHancler("widget-1"));
  widget2.addClickHandler(new MyClickHancler("widget-2"));

答案 1 :(得分:1)

嗯,这很简单,Manolo的回答基本上解决了它,你只需要稍微改进一下:

public abstract class EvenClickHandler implements ClickHandler {
    private boolean eventClick= true;

    public void onClick(ClickEvent event) {
        if (eventClick = !eventClick) {
          onEvenClick(event);
        }
    }


    protected abstract void onEvenClick(ClickEvent e);

}

...

listBox.addClickHandler(new EvenClickHandler (){

   protected void onEvenClick(ClickEvent e){
      lastSelection = listBox.getSelectedIndex();
   }

});