Based on the JavaFX EventHandler<T> it is quite simple to create a listener for a specific action. For the sake of argument, code would look as such :
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Hello World");
}
});
Now let’s say I wanted to have more complex things be processed on this event (let’s say it takes me 50-100 lines of code). I could use the same approach and have all this code within my handler, and thus in my controller.
If I wanted to have this slightly cleaner looking I could implement the EventHandler<T> interface. This would look as such :
public class LoginHandler implements EventHandler<ActionEvent> {
// list of parameters passed
public LoginHandler(ResourceBundle resources) {
//Resources along with other paramters I need to access
this.resources = resources;
}
@Override
public void handle(ActionEvent event) {
//...Logic goes here
System.out.println("doing my logic here - 50 to 100 lines");
((Node)(event.getSource())).getScene().getWindow().hide();
}
}
Such an approach works, but I do have to pass as a parameter all the objects (wether that be a button, label, textbox, etc) and ResourceBundle (if trying to internationalize my app).
Is there any way to access all this information? Bascially access the controller from the EventHandler? Or is the best practice to leave everything in the controllers?
In my opinion, if the logic to be done in the handle method is related to view (ie the controls in FXML) it should be kept in the controller. No one other than controller have to know the FXML structure. If you are going to do a general and common logic in the extended eventHandler, in addtion to other parameters, also pass the controller instance to this eventHandler. Then delegate view related jobs to the controller, like controller.updateView(params) for example. Those controllers can also implement a common interface that has the updateView(params) method signature.