JavaFX:我如何才能最好地将Label放在一个Shape中心?

Bas*_*ium 4 javafx

假设我已经在屏幕上显示了一个Shape.例如:

Circle circle = new Circle(x, y, radius);
circle.setFill(Color.YELLOW);
root.getChildren().add(circle);
Run Code Online (Sandbox Code Playgroud)

我想在Circle上面创建一个Label,使得Label在Circle中居中,字体大小最大化以适应Circle内部等.

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

预先感谢您的帮助!我是JavaFX的新手,并不是最初在编程方面经验丰富的所有人,所以如果我能通过我的研究找到这个,我会道歉.

jew*_*sea 8

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

点

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有关

相关问题的答案讨论了文本的不同边界类型(例如Visual bounds),以备您需要时使用.