javafx文本中心位于x和y

tp5buhyn  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(242)

如何将文本的中心动态定位在圆的中心?当前文本是用给定的x和y坐标在左下角创建的,但是我希望它们是文本的中心(红点是圆的中心,这是我想要的文本中心)。
电流:

预期:

public class CenteredText extends Application {

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

    @Override
    public void start(Stage mainStage) throws Exception {
        Pane pane = new Pane();
        Circle circle = new Circle(250, 250, 100);
        Circle innerCircle = new Circle(250, 250,
                98);
        innerCircle.setFill(Color.WHITE);
        Text text = new Text(250, 250, "test" );
        // coords given to text
        Circle coords = new Circle(250, 250, 1);
        pane.getChildren().addAll(circle, innerCircle, text, coords);

        BorderPane root = new BorderPane();
        root.setCenter(pane);
        mainStage.setScene(new Scene(root, 500, 500));
        mainStage.show();
    }

  }
lyfkaqu1

lyfkaqu11#

若要垂直居中文本,请将其文本原点设置为“居中”。
你需要自己计算x坐标。因为你想要文本总宽度的一半保持在250,你需要知道总宽度才能做数学运算。
css不会应用于节点,直到它们出现在场景中。但您可以放弃css,直接设置字体,这样程序就可以立即知道文本对象的适当首选宽度:

Text text = new Text(250, 250, "test");
text.setFont(Font.font("Arial", 24));
double width = text.prefWidth(-1);
text.setX(250 - width / 2);
text.setTextOrigin(VPos.CENTER);
e0uiprwp

e0uiprwp2#

标签控件将为您执行以下操作:

public class Main extends Application {

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

    @Override
    public void start(Stage stage) {
        stage.setTitle("Centered Text");
        Circle circle = new Circle(100);
        Circle innerCircle = new Circle(98);
        innerCircle.setFill(Color.WHITE);
        StackPane circles = new StackPane(circle, innerCircle);
        Label label = new Label("test", circles);
        label.setContentDisplay(ContentDisplay.CENTER);

        Pane p = new Pane(label);
        Scene scene = new Scene(p);
        stage.setScene(scene);
        stage.show();
    }
}

相关问题