如何在GWT 1.6中向复合面板添加事件处理程序

时间:2009-05-06 19:01:23

标签: gwt handlers event-handling

这可能是一件非常简单的事情,但我不知道如何实现以下内容。

package mods.client.resultSelector;

import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;

public class MousyAbsolutePanel extends Composite implements MouseDownHandler {

    AbsolutePanel abs = new AbsolutePanel();

    public MousyAbsolutePanel(int width){
        System.out.println("MousyAbsolutePanel being created with width:" + width);
        initWidget(abs);
        abs.setWidth(String.valueOf(width));
        abs.setHeight("100%");
        abs.setStyleName("mousyAbsolutePanel");
    }

    public void onMouseDown(MouseDownEvent event) {
        System.out.println("onMouseDown()");
    }

}

我想拥有一个可以接受鼠标事件的absolutePanel。但是,在Composite对象中,我不知道如何将我编写的处理程序(onMouseDown()事物)与abs变量绑定。简而言之,我希望abs AbsolutePanel在点击时响应,但AbsolutePanels不会自然地接受点击事件。我该怎么做呢?

如果这很简单,请提前道歉,但我不太清楚如何实现这种行为,我在搜索过程中没有看到它。

4 个答案:

答案 0 :(得分:5)

在这种情况下,扩展Composite可能不是最佳选择,除非您故意阻止访问在构造函数中创建的AbsolutePanel。如果您扩展AbsolutePanel,您将能够重用代码来添加/删除小部件等。

以下是我建议你这样做的方法:

package mods.client.resultSelector;

import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.HasMouseDownHandlers;
import com.google.gwt.user.client.ui.AbsolutePanel;


public class MousyAbsolutePanel extends AbsolutePanel implements
                         MouseDownHandler,HasMouseDownHandlers {

    public MousyAbsolutePanel(int width) {
        System.out.println("MousyAbsolutePanel being created with width:" + width);

        this.setWidth(String.valueOf(width));
        this.setHeight("100%");
        this.setStyleName("mousyAbsolutePanel");

        this.addMouseDownHandler(this);
    }

    /** 
     * MouseDownHandler
     */
    public void onMouseDown(MouseDownEvent event) {
        System.out.println("onMouseDown()");
    }

    /**
     * HasMouseDownHandlers - Code to add handlers to the panel
     */  
    public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
         return addDomHandler(handler, MouseDownEvent.getType());
    }

}

然后您可以像访问AbsolutePanel一样访问MousyAbsolutePanel,但使用其他事件处理程序,样式等。

答案 1 :(得分:1)

这是另一篇可能有帮助的帖子:

Adding ClickHandler to div which contains many other widget

致电sinkEvents(Event.ONCLICK)然后仅使用ClickHandler添加addHandler对我来说非常有用。

答案 2 :(得分:0)

学习如何/做什么最好的办法就是看一个例子。例如,FocusWidget类(实现HasClickHandlers)。

具体来说,请查看addClickHandler()方法,并跟踪它。

答案 3 :(得分:0)

致电initWidget(Widget)后,Composite将正确代理事件注册。因此,您只需致电MousyAbsolutePanel继承的addDomHandler(...)