gpt4 book ai didi

JavaFX:如何最好地将标签放置在形状的中心?

转载 作者:行者123 更新时间:2023-12-04 20:43:05 24 4
gpt4 key购买 nike

假设我已经在屏幕上有了一个形状。例如:

Circle circle = new Circle(x, y, radius);
circle.setFill(Color.YELLOW);
root.getChildren().add(circle);

我想创建一个“在”圆圈上的标签,使标签在圆圈中居中,字体大小最大化以适合圆圈内,等等。

我可以看到如何通过绑定(bind)来实现这一点,但如果这些东西的位置/大小在运行时永远不会改变,这似乎是不必要的复杂。

预先感谢您的帮助!我对 JavaFX 很陌生,而且并不是所有的编程经验,所以如果我应该能够通过我的研究发现这一点,我深表歉意。

最佳答案

使用 StackPane自动将文本居中在形状的顶部。

spot

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.*;
import javafx.stage.Stage;

// java 8 code.
public class Circular extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}

@Override
public void start(final Stage stage) throws Exception {
Text text = createText("Xyzzy");
Circle circle = encircle(text);

StackPane layout = new StackPane();
layout.getChildren().addAll(
circle,
text
);
layout.setPadding(new Insets(20));

stage.setScene(new Scene(layout));
stage.show();
}

private Text createText(String string) {
Text text = new Text(string);
text.setBoundsType(TextBoundsType.VISUAL);
text.setStyle(
"-fx-font-family: \"Times New Roman\";" +
"-fx-font-style: italic;" +
"-fx-font-size: 48px;"
);

return text;
}

private Circle encircle(Text text) {
Circle circle = new Circle();
circle.setFill(Color.ORCHID);
final double PADDING = 10;
circle.setRadius(getWidth(text) / 2 + PADDING);

return circle;
}

private double getWidth(Text text) {
new Scene(new Group(text));
text.applyCss();

return text.getLayoutBounds().getWidth();
}
}

有关的
  • how to put a text into a circle object to display it from circle's center?

  • 如果您需要,相关问题的答案讨论了文本的不同边界类型(例如 Visual 边界)。

    关于JavaFX:如何最好地将标签放置在形状的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23258605/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com