使用 javaFX 对齐文本时遇到问题

Having trouble aligning text using javaFX

今天刚开始学javaFX,对文本节点真是一头雾水。我制作的文字不会居中对齐。我尝试使用 Pane、GridPane,现在使用 VBox。这有什么关系吗? -fx-text-alignment: center; 但这也没有用。我对此很陌生。谢谢任何人的帮助!这是我的代码:

        package dev.angarc.game;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class Game extends Application{

    public static void main(String[] args){
        launch(args);
    }

    @Override
    public void start(Stage stage){

        VBox vbox = new VBox();

        // Component stuff

        Text text = new Text("This Text Wont Align To The Center!");
        text.setFont(Font.font("Arial", FontWeight.NORMAL, FontPosture.REGULAR, 20));
        text.setTextAlignment(TextAlignment.CENTER);

        // adding to the pane
        vbox.getChildren().add(text);

        // Stuff to set up the window.
                stage.setScene(new Scene((vbox), 640, 430));
                stage.setTitle("Text Game");
                stage.setResizable(false);
                stage.show();

    }

}

您想告诉您的 CONTAINER 使用什么对齐方式。

您可以使用窗格的 setAlignment() 方法来管理节点和窗格的对齐方式。对齐常量在 javafx.geometry 包中的枚举类型中可用。

HBox hbox= new HBox();
hbox.setAlignment(Pos.CENTER);//The overall alignment of children within the hbox's width and height.

如果您想使用 FXML

<VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
         <children>
            <Text strokeType="OUTSIDE" strokeWidth="0.0" text="Text" />
         </children>
      </VBox>