Can we use create and use custom EventHandler classes in JAVAFX

javafxjavafx-2

I have a question on the Event Handling in JavaFX. As per the tutorial (and other examples that I came across), event handling is carried the following way in JavaFX:

Button addBtn = new Button("Add");
addBtn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
            System.out.println("Add Clicked");
    }
});

But, I am wondering, if I can "handle" the button click the following way:

Button addBtn = new Button("Add");
addBtn.setOnAction(new addButtonClicked());

where addButtonClicked() is my own Class (with it's own set of methods and functionality) that I have defined and written to handle the actions for the button click.

Is there a way to attach my own event handler classes for buttons in JavaFX?

Best Answer

The EventHandler is an interface class. So, it should be "implements" not "extends"

private static class AddButtonClicked implements EventHandler<ActionEvent> {
     @Override
     public void handle(ActionEvent event) {
          System.out.println("My Very Own Private Button Handler");
     }
}
Related Topic