I am trying to implement EventHandler<MouseEvent>
, and EventHandler<KeyEvent>
in the same class. However, I can't, since it says EventHandler
is a single class. How can I create a class that is both a mouse event handler and a key event handler?
Asked
Active
Viewed 25 times
0

MCMastery
- 3,099
- 2
- 20
- 43
-
You can't, but you could make 2 nested/anonymous classes that implement each. – Jorn Vernee Sep 21 '16 at 15:37
-
It's not really clear why you would want to do this. – James_D Sep 21 '16 at 18:25
-
@James_D so I can have a class that is both a mouse event handler and a key event handler, since an EventHandler> is required for JavaFX event handling – MCMastery Sep 21 '16 at 18:26
-
Why would you want such a thing though? The methods `setOnXXX(...)` all require specific event handlers (with a specific event type), and the `addEventHandler(EventType
, EventHandler super T>)` method (and similarly `addEventFilter(...)`) take specific types of event handler too. Suppose you had a class that implemented both, how would you actually use it? If the behavior is identical for either type of event, you can just use a `EventHandler – James_D Sep 21 '16 at 18:31` or `EventHandler `; if the behavior is different, you may as well have two handler classes. -
@James_D Oh true, I didn't think of using a generic Event... thanks – MCMastery Sep 21 '16 at 18:34
-
Alternatively just define the behavior in a method: `private void someMethod(Event e) { ...}` and use lambdas: `node.setOnKeyPressed(e -> someMethod(e));`, `node.setOnMouseClicked(e -> someMethod(e));`, or even method references: `node.setOnKeyPressed(this::someMethod);` etc. – James_D Sep 21 '16 at 18:36
-
@James_D that's actually what I ended up doing, I just wanted a more "object-oriented design" – MCMastery Sep 21 '16 at 18:38