JavaFX - centered Text in Scene

前端 未结 2 459
你的背包
你的背包 2021-01-20 07:13

I\'ve got a JavaFX Text,Scene and Group

Text waitingForKey
Scene scene
Group root

I have a string St

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 08:04

    Specify TextAlignment.CENTER for the Text and use a layout like StackPane that "defaults to Pos.CENTER."

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.text.Font;
    import javafx.scene.text.Text;
    import javafx.scene.text.TextAlignment;
    import javafx.stage.Stage;
    /**
     * @see http://stackoverflow.com/a/37541777/230513
     */
    public class Test extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            Text waitingForKey = new Text("Level 2 \n\n" + "Press ENTER to start a new game");
            waitingForKey.setTextAlignment(TextAlignment.CENTER);
            waitingForKey.setFont(new Font(18));
            waitingForKey.setFill(Color.ALICEBLUE);
            StackPane root = new StackPane();
            root.getChildren().add(waitingForKey);
            Scene scene = new Scene(root, 320, 240, Color.BLACK);
            primaryStage.setTitle("Test");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题