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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…