How to handle multiple event types from one class in JavaFX?

懵懂的女人 提交于 2019-12-23 02:36:35

问题


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>

回答1:


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> and EventHandler<MouseEvent> conflict with each other, that is why you end up with the error.

Like so...

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.



来源:https://stackoverflow.com/questions/31794167/how-to-handle-multiple-event-types-from-one-class-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!