Java Reference
In-Depth Information
Accessing the Stage from the Scene
To obtain a reference to the Stage instance from the Scene , we use a property in the Scene class named window .
The accessor method for this property appears in the following snippet from Listing 2-2 to get the x and y co-ordinates
of the Stage on the screen.
labelStageX.textProperty().bind(new SimpleStringProperty("Stage x: ")
.concat(sceneRef.getWindow().xProperty().asString()));
labelStageY.textProperty().bind(new SimpleStringProperty("Stage y: ")
.concat(sceneRef.getWindow().yProperty().asString()));
Inserting a Node into the Scene's Content Sequence
Sometimes it is useful to add a node dynamically to the children of a UI container class. The code snippet from
Listing 2-2 that follows demonstrates how this may be accomplished by dynamically adding a Text node to the children
of the FlowPane instance:
// Define an unmanaged node that will display Text
Text addedTextRef = new Text(0, -30, "");
addedTextRef.setTextOrigin(VPos.TOP);
addedTextRef.setFill(Color.BLUE);
addedTextRef.setFont(Font.font("Sans Serif", FontWeight.BOLD, 16));
addedTextRef.setManaged(false);
// Bind the text of the added Text node to the fill property of the Scene
addedTextRef.textProperty().bind(new SimpleStringProperty("Scene fill: ").
concat(sceneRef.fillProperty()));
// Add the Text node to the FlowPane
((FlowPane) sceneRef.getRoot()).getChildren().add(addedTextRef);
This particular Text node is the one at the top of the Scene shown in Figures 2-6 and 2-7 , in which the value of the
Scene 's fill property is displayed. Note that in this example the managed property of the addedTextRef instance is set to
false, so its position isn't governed by the FlowPane . By default, nodes are “managed,” which means that their parent
(the container to which this node is added) is responsible for the layout of the node. By setting the managed property to
false, the developer is assumed to be responsible for laying out the node.
CSS Styling the Nodes in a Scene
A very powerful aspect of JavaFX is the ability to use CSS to style the nodes in a Scene dynamically. You used this
capability in Step 6 of the previous exercise when you clicked changeOfScene.css to change the appearance of the UI
from what you saw in Figure 2-6 to what was shown in Figure 2-7 . Also, in Step 7 of the exercise, the appearance of the
UI changed back to what was shown in Figure 2-6 when you selected the onTheScene.css radio button. The relevant
code snippet from Listing 2-2 is shown here:
sceneRef.getStylesheets().add("onTheScene.css");
...code omitted...
// When the selected radio button changes, set the appropriate stylesheet
toggleGrp.selectedToggleProperty().addListener((ov, oldValue, newValue) -> {
String radioButtonText = ((RadioButton) toggleGrp.getSelectedToggle())
.getText();
 
Search WWH ::




Custom Search