A handler for ActionEvents to be used with buttons is:
val actionHandler: EventHandler<ActionEvent> = object: EventHandler<ActionEvent> {
override fun handle(event: ActionEvent?): Unit { /* do nothing */ }
}
BUT, to define a handler for MouseEvents requires a completely different
structure:
/**
Interface:
interface EventHandler<T extends Event> {
void handle(T event)
}
Hierarchy:
Event
ActionEvent
InputEvent
* MouseEvent
* KeyEvent
*/
import javafx.event.*
import javafx.scene.input.*
fun main(args: Array<String>) {
val actionHandler: EventHandler<ActionEvent> = object: EventHandler<ActionEvent> {
override fun handle(event: ActionEvent?): Unit { /* do nothing */ }
}
val mouseHandler: EventHandler<in MouseEvent?> = object: EventHandler<MouseEvent?> {
override fun handle(event: MouseEvent?): Unit { /* do nothing */ }
}
}
The problem is thatNode.setOnMousePressed() method expects parameter of type EventHandler<in MouseEvent?>?, which means that it accepts EventHandler with any supertype of MouseEvent? in angle brackets. MouseEvent is not a subtype of MouseEvent?, so EventHandler<MouseEvent> is not a subtype of EventHandler<in MouseEvent?>
What you can do about it:
subclass from EventHandler<MouseEvent?> or EventHandler<in MouseEvent?>;
provide external annotations with different signature for Node.setOnMousePressed(): setOnMousePressed(EventHandler<in MouseEvent>).