In my object oriented programming class, our recent topic has been event-driven programming through JavaFX. The concepts have been relatively interesting, though at times quite confusing to me. One thing that I have struggled quite greatly to understand is the workings of the setOnAction() method.
As my instructor said, this method takes in an object of a class that has a handle method, and calls that handle method whenever an event is fired.
For example in our start method:
class MyHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent actionEvent) {
System.out.println("Handled");
}
}
Button button = new Button();
button.setOnAction(new MyHandler());
However, I'm unable to understand how this works under the hood. How exactly does the setOnAction method "know" to call the handle method of the MyHandler object? Is it possible to implement my own version of a setOnAction, in which I call a specifically named method of any passed in object?
And what if we don't implement a handle method at all, but instead say, a fakeHandle method, like this.
class MyHandler {
public void fakeHandle(ActionEvent actionEvent) {
System.out.println("Handled");
}
}
Button button = new Button();
button.setOnAction(new MyHandler());
Would our code still work?