Java Reference
In-Depth Information
Listing 5-2.
Example of Centering Text in a Scene
public class CenterUsingBind extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Text text = new Text("JavaFX Reversi");
text.setTextOrigin(VPos.TOP);
text.setFont(Font.font(null, FontWeight.BOLD, 18));
Scene scene = new Scene(new Group(text), 400, 100);
text.layoutXProperty().bind(scene.widthProperty().subtract(text.prefWidth(-1)).divide(2));
text.layoutYProperty().bind(scene.heightProperty().subtract(text.prefHeight(-1)).divide(2));
primaryStage.setScene(scene);
primaryStage.show();
}
}
Here are some specific points to highlight about Listing 5-2:
textOrigin
property of
Text
is
BASELINE
, which aligns to the bottom
of the letters, not including descenders. We chose to use
TOP
instead, which makes the origin
line up with the top of the letters. This makes
Text
behave similarly to most other
Nodes
, and is
much easier to center.
•
The default value for the
Text
node to a
Group
to add it to the
Scene
, which expects a container
of type
Parent
. There are better options than using a
Group
, as we show in the next section,
because this disables any automatic resizing.
•
We have to add the
prefWidth
and
prefHeight
we pass in a parameter of -1 for the
counterdimension, because this does not affect the returned dimensions for
Text
nodes. (
Text
nodes have no content bias.)
•
When getting the
Running this program produces a window where the title stays centered even if you resize the frame, as shown in
Figure
5-4
.
Figure 5-4.
A
Text
node centered within a
Scene
using bind
Search WWH ::
Custom Search