Tuesday, August 25, 2009

JavaFX onKeyTyped for a Scene [Update]

Since javaFX 1.2 nodes have to set the "focusTraversable" property to "true" in order the receive key events.

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 {
focusTraversable: true
content: [
onKeyTyped: function( e: KeyEvent) : Void {

Post a Comment