Monday, February 2, 2009

JavaFX onKeyTyped for a Scene

keyTyped events are easy to use in JavaFX. Just add a function to onKeyTyped on a node and this node will be notified if a key is typed.

But what if you start with an empty scene. There are no nodes which can receive the event. And there is no onKeyTyped for a scene or stage.

I found two solutions for this problem. Both are some kind of a hack but they work:

1. Create a CustomNode without any graphics and just a onKeyTyped and add this to the scene content.

2. (my preferred solution) Use a Group which is empty at the beginning and later contains the scenes nodes. Groups do have onKeyTyped.

Here is an example:

var stage = Stage {
title: "Application title"
fullScreen: true
scene: Scene {
content: [
Group {
content: [
]
onKeyTyped: function( e: KeyEvent) : Void {
System.out.println("Hello");
}
}
]
}
}

Post a Comment