javabuttonjavafxactionevent

How to set an instance of the EventHandler interface as the action for a button


I am trying to set the action of a button by passing an instance of the EventHandler<> interface to its setOnAction() method, however it is not working.

Class 1:

public class Class1 {
       
   private Class2 class2;
   private Button buttonDelete = null;

   private Button getButtonDelete() {
       if (buttonDelete == null) {
           buttonDelete = new Button("Delete");
           buttonDelete.setOnAction(class2);
       }
       return buttonDelete;
   }
}

Class 2:

public class Class2 implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent event) {
        // do something
    }
}

Solution

    1. Short answer :
    public Class1(Class2 class2){
    this.class2 = class2;
    }
    

    To call the constructor : new Class1(new Class2()); the handle method will be called automatically when the event triggred.

    1. Long answer, using anonymous classes is better for button event handling so learn about anonymouse classes and lambda expressions, good learning.