我如何从“事件"中获得object 发生此事件的对象? [英] How do I get from the "Event" object the object on which there was this event?

查看:27
本文介绍了我如何从“事件"中获得object 发生此事件的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UIBinder 在 GWT 上开发应用程序,但遇到了问题.在我的用户界面中可以有很多相同的元素(例如小部件).所有元素都必须有处理鼠标点击事件的处理程序.我想编写一个通用处理程序,它能够识别导致事件的小部件并对其进行处理.现在我为每个对象都有一个小部件来描述相同的处理程序.我该如何解决这个问题?

I am developing an application on GWT with UIBinder and I have a problem. In my user interface can be a lot of the same elements (eg widgets). All elements must have handlers that will catch the mouse click event. I want to write a universal handler that will be able to identify the widget that caused the event and handle it instead. Now I have a widget for each object to describe the same handler. How can I solve this problem?

推荐答案

您必须将源对象强制转换为您期望的对象.getSource() 方法只为您提供一个对象,但您无法从中访问任何信息(例如,从 Button 中,您首先必须将其转换为一个按钮).

You have to cast the source object to the object you expect. The getSource() method only delivers you an object, but you can't access any information from it (e.g. from a Button, you first have to cast it to a button).

这是一个例子:

    Button bt = new Button("click");
    bt.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            Object soruce = event.getSource();

            if (soruce instanceof Button) {  //check that the source is really a button
                String buttonText = ((Button) soruce).getText();  //cast the source to a button
                RootPanel.get().add(new Label(buttonText));
            } else {
                RootPanel.get().add(new Label("Not a Button, can't be..."));
            }
        }
    });

    RootPanel.get().add(bt);

这当然也适用于 UiBinder 按钮:

This of course also works for UiBinder Buttons:

@UiHandler("button")
void onClick(ClickEvent e) {

    Object soruce = e.getSource();

    if(soruce instanceof Button){
        String buttonText = ((Button)soruce).getText();
        RootPanel.get().add(new Label(buttonText));
    }
    else {
        RootPanel.get().add(new Label("The event is not bound to a button"));
    }
}

如果您不知道元素的类型,或者事件绑定到多个元素,则必须首先检查所有可能的类型,然后执行正确的操作.

If you don't know the type of your element, or the event is bound to more than one element, you have to check for all possible types first, and then perform the right action.

这篇关于我如何从“事件"中获得object 发生此事件的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆