By Alvin Alexander. Last updated: May 23, 2020
As a brief note, here are a few examples of how I add some keystroke handlers/listeners to a JavaFX project written in Scala:
// add keystroke listeners/handlers to the scene
def addKeystrokeHandlers(scene: Scene, stage: Stage, theMainPane: MainSplitPane): Unit = {
configureCommandMHandler(scene, stage)
// other code was here ...
}
// Minimize (needed to implement manually)
private def configureCommandMHandler(scene: Scene, mainStage: Stage): Unit = {
val keyComboCommandM: KeyCombination = new KeyCodeCombination(
KeyCode.M,
KeyCombination.META_DOWN
)
scene.addEventHandler(KeyEvent.KEY_RELEASED, (event: KeyEvent) => {
if (keyComboCommandM.`match`(event)) {
mainStage.setIconified(true)
}
})
}
The keys for this keystroke-handler solution are knowing how to use the KeyCodeCombination
, and how to handle a KeyEvent
on the JavaFX Scene
. Everything besides that involves implementing your custom logic, such as minimizing the Scene/Stage/Frame in this example. I also use this technique to increase and decrease font size in text editors, like this:
private def decreaseFontSizeHandler(scene: Scene, theMainPane: MainSplitPane): Unit = {
val decreaseFontSizeKeyCombination: KeyCombination = new KeyCodeCombination(
KeyCode.MINUS,
KeyCombination.META_DOWN
)
scene.addEventHandler(KeyEvent.KEY_RELEASED, (event: KeyEvent) => {
if (decreaseFontSizeKeyCombination.`match`(event)) {
theMainPane.decreaseFontSize()
}
})
}
and this:
def decreaseFontSize(): Unit = {
fontSize -= 1
editorTextArea.setFont(Font.font("Monaco", FontWeight.NORMAL, fontSize))
notesTextArea.setFont(Font.font("Monaco", FontWeight.NORMAL, fontSize))
}
Some of that code can be improved, but in summary, if you want to see how to implement JavaFX keystroke handlers/listeners in Scala or Java code, I hope these examples are helpful.