Sam Claus
Sam Claus

Reputation: 1971

How to handle multiple event types from one class in JavaFX?

In JavaFX, is it possible to handle multiple event types (e.g. ActionEvent, MouseEvent, etc.) from one class, without anonymous EventHandlers? I tried the following, but that just created a compile-time error.

public class GUI extends Application implements EventHandler<ActionEvent>,
                                                EventHandler<MouseEvent>

Upvotes: 2

Views: 5635

Answers (1)

user4979686
user4979686

Reputation:

Yes, but not in the way that you are expecting.

You cannot, as far as I know, implement the same interface twice, even with different types.

EventHandler<ActionEvent> and EventHandler<MouseEvent> conflict with each other, that is why you end up with the error.

Like so...

class CustomEventHandler implements EventHandler<Event>{

    public void handleActionEvent(ActionEvent ke){
        //handle event
    }

    public void handleMouseEvent(MouseEvent me){
        //handle event
    }

    @Override
    public void handle(Event event) {
        //handle event testing
    }

}

Then you simply test if the Event is of mouse type or action type, then handle the event from that function.

Upvotes: 5

Related Questions