Java Reference
In-Depth Information
Centering Revisited Using a
StackPane
In the previous section you saw how to center text using the bind operator. That is one way to center text, but we show
you an alternative approach using the
StackPane
class, which has built-in capabilities for aligning nodes.
The
StackPane
class is a layout container that allows you to layer nodes on top of each other to create composite
effects. For all the nodes in a
StackPane
to be visible, the upper nodes must be shaped or transparent so that it is
possible to see through them. Table
5-2
lists some of the functions that you can use to add and align nodes in a
StackPane
.
Table 5-2.
Functions on the
StackPane
Layout Class
Name
Defined In
Description
setAlignment(Pos)
StackPane
Sets the default alignment of nodes added to a
StackPane
setAlignment(Node, Pos)
StackPane
Static function to set the alignment for a given node
when added to a
StackPane
getChildren():ObservableList<Node>
Pane
A sequence of children that will be stacked from back
to front
The order of the children in the content sequence controls the z-order of the
StackPane
, with the first element
(index 0) appearing on the bottom and the last (index size -1) on the top. The
setAlignment
functions can be used to
control the alignment of nodes that do not fill all the available space in the
StackPane
. When the node alignment is
set, that gets precedence; otherwise the default alignment for the
StackPane
is used. Finally, if neither is set, a default
value of
CENTER
is used to align nodes.
To build on the previous example, we invert the text and background by adding a black
Ellipse
to the scene that
covers most of the background and by changing the color of the
Text
node to white. Also, to simplify the alignment
and allow layering of nodes, we use a
StackPane
instead of bind to lay out the nodes, as shown in Listing 5-3.
Listing 5-3.
Example of Using a
StackPane
to Overlay and Align Nodes
public class CenterUsingStack extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Text text = new Text("JavaFX Reversi");
text.setFont(Font.font(null, FontWeight.BOLD, 18));
text.setFill(Color.WHITE);
Ellipse ellipse = new Ellipse();
StackPane stack = new StackPane();
stack.getChildren().addAll(ellipse, text);
Scene scene = new Scene(stack, 400, 100);
ellipse.radiusXProperty().bind(scene.widthProperty().divide(2));
ellipse.radiusYProperty().bind(scene.heightProperty().divide(2));
primaryStage.setScene(scene);
primaryStage.show();
}
}
Search WWH ::
Custom Search