【发布时间】:2013-12-09 17:48:38
【问题描述】:
在我能找到的几乎所有示例中,JavaFX 事件处理程序都是作为匿名内部类创建的, 像这样:
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount()>1) {
System.out.println("double clicked!");
}
}
});
但是,我真的很讨厌匿名内部类(丑陋!!!),而且我也不想为每个事件处理程序创建单独的类。我想像 FXMLLoader 那样使用现有方法作为事件处理程序。我的第一个想法是使用反射和泛型,这就是我想出的:
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;
}
}
您传递了所需的事件类、处理程序实例和将处理事件的方法名称,并返回所需的 EventHandler。它有效,但看起来不是很优雅。有人有更好的主意吗?
【问题讨论】:
标签: reflection event-handling javafx-2