如何从“事件”中获得对象有这个事件的对象? [英] How do I get from the "Event" object the object on which there was this event?
问题描述
你必须将source对象转换为你期望的对象。 getSource()方法只提供一个对象,但是你不能访问任何信息(例如从一个Button,你首先必须将其转换成一个按钮)。
这是一个例子:
按钮bt = new Button(click);
bt.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event){
Object soruce = event.getSource();
if(soruce instanceof Button){//检查源是否真的是一个按钮
String buttonText =((Button)soruce).getText(); //将源转换为按钮
RootPanel.get()。add(new Label(buttonText));
} else {
RootPanel.get()。add(new Label(Not a Button,can not be。 ..));
}
}
});
RootPanel.get()。add(bt);
这当然也适用于UiBinder按钮:
void onClick(ClickEvent e){
Object soruce = e.getSource();
@UiHandler(button
if(soruce instanceof Button){
String buttonText =((Button)soruce).getText();
RootPanel.get()。add(new Label(buttonText));
}
else {
RootPanel.get()。add(new Label(事件未绑定到按钮));
}
}
如果您不知道元素的类型,或事件绑定到多个元素,您必须首先检查所有可能的类型,然后执行正确的操作。
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?
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).
Here is an example:
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);
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.
这篇关于如何从“事件”中获得对象有这个事件的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!