Search code examples
javafxsubclasssuperclasseventhandler

JavaFX: execute events in Sub- and in SuperClass


if I implement an onMouseClicked-EventHandler in a SuperClass like this:

public class SuperClass {
    public SuperClass() {
                
        setOnMouseClicked(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                System.out.println("Super reacted");
            }
        });
    }

And I implement an onMouseClicked-EventHandler in a SubClass of SuperClass like this:

public class SubClass extends SuperClass{
    public SubClass() {
                
        setOnMouseClicked(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                System.out.println("Sub reacted");
        });
    }
}

After clicking on a instance of SubClass the result in the console will be "Sub reacted". So the SuperClass does not notice the event.

How can I forward the event in a way, that all super classes react too? I thought of manually firing an event in the sub class, but it dosnt work.

Thank you for your help.


Solution

  • There exists two ways to register with widgets in JavaFX:

    • setOnMouseClicked (all the setOn... methods). The handler associated with setOnMouseClicked is unique: in your case the sub-class registration replaces the registration made in the super class.
    • addEventHandler (or AddEventFilter). In this case you can have multiple handlers that register with the same widget. These methods take as arguments: the type of event you want to listen; a instance of the type EventHandler<> that you can write as a callback or an anonymous class. In your case:
    addEventHandler(MouseEvent.MOUSE_CLICKED, evt -> {
     // ... 
    });
    

    or using an anonymous class:

    addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
       @Override
       public void handle(final MouseEvent evt) {
       }
    });
    

    Where evt is the triggered mouse click event.

    The use of addEventHandler should fix your issue.