In virtually all examples I could find, JavaFX event handlers are created as anonymous inner classes, like so:
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount()>1) {
System.out.println("double clicked!");
}
}
});
But, I really hate anonymous inner classes (UGLY!!!), and I also don't want to create separate classes for each and every event handler. I would like to use existing methods as event handlers, as FXMLLoader does. My first idea was to use reflection and generics, and this is what I came up with:
public final static <E extends Event> EventHandler<E> createEventHandler(
final Class<E> eventClass, final Object handlerInstance, final String handlerMethod) {
try {
final Method method = handlerInstance.getClass().getMethod(handlerMethod, eventClass);
return new EventHandler<E>() {
@Override
public void handle(E event) {
try {
method.invoke(handlerInstance, event);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
};
} catch (NoSuchMethodException | SecurityException e) {
return null;
}
}
You pass a required Event class, handler instance and method name which will handle the event, and required EventHandler is returned. It works, but it doesn't look very elegant. Does anyone have a better idea?