Monday, February 9, 2009

Dynamically Adding UI Elements to JavaFX Scene Content

JavaFX is nice to statically describe your UI elements. But what if you have to add something to the UI dynamically. E.g. The user presses a button and a new text should be added to the scene.

Well this is easy too. Just create the new element in the action code of the button and add it to the content using JavaFX's sequential (list) handling operations.

Here is an example: (Note: You have to create a variable for the stage in order to be able to access it).

var myX : Number = 50;
var myY : Number = 50;

var stage : Stage = Stage {
title: "Add text"
width: 250
height: 250
scene: Scene {
content: [
SwingButton {
text: "Add char"
action: function() {
var myChar = Text {
x: myX += 10,
y: myY += 10
content: "A"
}
insert myChar into
stage.scene.content;
}
}
]
}
}
Post a Comment