I've got a JavaFX Text
,Scene
and Group
Text waitingForKey
Scene scene
Group root
I have a string String waitingForKeyString
which I'm adding to waitingForKey
and I want to have a center align.
The problem is that sometimes the string has two sentences and I can't aligned it
String waitingForKeyString= " Level 2 \n\n" + "Press ENTER to start a new game";
OR
String waitingForKeyString= " Press ENTER \n"+ "to start the game", messageString="";
THEN
Scene scene = new Scene(root,SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK);
waitingForKey.setText(waitingForKeyString);
root.getChildren().add(waitingForKey);
So how could I align this to center? When I tried to align first waitingForKeyString
I destroyed the second `waitingForKeyString and vicecersa.
You could use a StackPane
as root of your Scene
as it has an alignmentProperty
.
If you want individually align Nodes
in the StackPane
you can use public static void setAlignment(Node child, Pos value)
method of StackPane
.
Example (one Text is aligned in CENTER, another one is aligned in TOP LEFT)
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
StackPane root = new StackPane();
Text text2 = new Text("I will be aligned TOPLEFT");
Text text = new Text(" Level 2 \n\n" + "Press ENTER to start a new game");
text.setTextAlignment(TextAlignment.CENTER);
root.getChildren().addAll(text2, text);
StackPane.setAlignment(text2, Pos.TOP_LEFT);
StackPane.setAlignment(text, Pos.CENTER);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With