Search code examples
javajavafxeventsevent-handling

JavaFx: custom event either doesn't get fired or not listened to


Minimal code example:

public class HelloApplication extends Application implements EventHandler<HelloApplication.MyEvent> {

    public class MyEvent extends Event {
        public static final EventType TYPE = new EventType<>(Event.ANY, "MyType");
        public MyEvent() {
            super(TYPE);
        }
    }

    @Override
    public void handle(MyEvent myEvent) {
        System.out.println("Event handled!");
    }

    @Override
    public void start(Stage stage) throws IOException {
        BorderPane root = new BorderPane();
        stage.setScene(new Scene(root, 640, 480));
        Button button1 = new Button("Click");
        button1.setOnAction(event -> {
            button1.fireEvent(new MyEvent());
            System.out.println("Event fired!");
        });
        root.setTop(button1);
        Button button2 = new Button("Clack");
        button2.addEventHandler(MyEvent.TYPE, this);
        root.setBottom(button2);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

I get "Event fired!" in my console but not "Event handled!".

It works when I add the event listener to button1. Am I missing something obvious? Is it not possible to fire an event on A and listen to it on B?


Solution

  • The code

    button2.addEventHandler(MyEvent.TYPE, this);
    

    registers the current HelloApplication instance (this) as an event handler with button2. This means that whenever button2 fires an event with event type MyEvent.TYPE, then this.handle(...) will be invoked.

    However, in the code you posted, button2 never fires such an event. The only time that event is fired is via the code

    button1.fireEvent(new MyEvent());
    

    which of course causes button1 to fire the event, not button2.