Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - How do I get from the "Event" object the object on which there was this event?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...