【问题标题】:Having trouble aligning text using javaFX使用 javaFX 对齐文本时遇到问题
【发布时间】:2016-11-25 16:34:23
【问题描述】:

我今天刚开始学习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();

    }

}

【问题讨论】:

  • 来自Text.setTextAlignment javadoc:“边界框的宽度由最宽的行定义。注意:在单行文本的情况下,节点的宽度由文本的宽度,对齐设置无效。”请参阅 Tomas 的回答以了解如何在父布局容器中对齐单行文本。

标签: java css text javafx components


【解决方案1】:

你想告诉你的 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>

【讨论】:

    猜你喜欢
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2021-04-14
    • 2012-12-18
    • 2021-11-17
    • 2017-10-12
    • 2015-01-20
    相关资源
    最近更新 更多