Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX - centered Text in Scene

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 waitingForKeyand 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 waitingForKeyStringI destroyed the second `waitingForKeyString and vicecersa.

like image 233
Valentin Emil Cudelcu Avatar asked Dec 24 '22 05:12

Valentin Emil Cudelcu


1 Answers

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);
    }
}
like image 117
DVarga Avatar answered Dec 28 '22 05:12

DVarga