如何在JavaFX中处理来自一个类的多个事件类型? [英] How to handle multiple event types from one class in JavaFX?
问题描述
在JavaFX中,是否可以从一个类处理多个事件类型(例如ActionEvent,MouseEvent等),而无需匿名的EventHandlers?我尝试了以下操作,但这只是创建了一个编译时错误。
In JavaFX, is it possible to handle multiple event types (e.g. ActionEvent, MouseEvent, etc.) from one class, without anonymous EventHandlers? I tried the following, but that just created a compile-time error.
public class GUI extends Application implements EventHandler<ActionEvent>,
EventHandler<MouseEvent>
推荐答案
是的,但不是你期望的方式。
Yes, but not in the way that you are expecting.
据我所知,你不能两次实现相同的界面,即使是不同的类型。
You cannot, as far as I know, implement the same interface twice, even with different types.
EventHandler< ActionEvent>和EventHandler< MouseEvent>
相互冲突,这就是你最终得到错误的原因。
EventHandler<ActionEvent> and EventHandler<MouseEvent>
conflict with each other, that is why you end up with the error.
像这样...
class CustomEventHandler implements EventHandler<Event>{
public void handleActionEvent(ActionEvent ke){
//handle event
}
public void handleMouseEvent(MouseEvent me){
//handle event
}
@Override
public void handle(Event event) {
//handle event testing
}
}
然后你只测试事件是鼠标类型还是动作类型,然后处理该函数的事件。
Then you simply test if the Event is of mouse type or action type, then handle the event from that function.
这篇关于如何在JavaFX中处理来自一个类的多个事件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!