Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading