javafx:将文本放在形状底部的组内

thigvfpy  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(327)

我有一个简单的代码,画一个圆并打印 Hello World! 文本。当前文本在圆内,而我希望它在它下面。圆和文本都在 Group .

import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class CircleArc  extends Application {
    @Override
    public void start(Stage applicationStage) {
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setFitToWidth(true);

        FlowPane flowPane = new FlowPane();
        flowPane.setOrientation(Orientation.HORIZONTAL);

        Circle circle = new Circle(100);
        circle.setFill(Color.GREEN);
        double rate = 0.6;
        Arc arc = new Arc(0, 0, 100, 100,
                0, -360*rate);
        arc.setType(ArcType.ROUND);
        arc.setFill(Color.GRAY);

        Text text = new Text("Hello World!");

        text.setLayoutX(text.getLayoutX() / 2);
        text.setLayoutY(text.getLayoutY());

        Group group = new Group();
        group.getChildren().add(circle);
        group.getChildren().add(arc);
        group.getChildren().add(text);

        flowPane.getChildren().add(group);

        scrollPane.setContent(flowPane);
        Scene scene = new Scene(scrollPane);
        applicationStage.setScene(scene);
        applicationStage.show();
    }

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

现在看起来是这样的:

但是我希望它看起来像这样:

我试着用 setLayout 方法,但它们不起作用。
编辑:
结果很简单

text.setLayoutX(text.getLayoutX() - 50);
text.setLayoutY(text.getLayoutY() + 120);

效果还不错。

kq0g1dla

kq0g1dla1#

使用标签。将圆设置为图形,将文本放在下面。

public class Main extends Application {

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

    @Override
    public void start(Stage stage) {
        stage.setTitle("Centered Text Under Graphic");

        Circle circle = new Circle(100);
        circle.setFill(Color.GREEN);
        double rate = 0.6;
        Arc arc = new Arc(0, 0, 100, 100,
            0, -360 * rate);
        arc.setType(ArcType.ROUND);
        arc.setFill(Color.GRAY);
        Group circles = new Group(circle, arc);

        Label label = new Label("Hello World!", circles);
        label.setContentDisplay(ContentDisplay.TOP);
        Pane p = new Pane(label);
        Scene scene = new Scene(p);
        stage.setScene(scene);
        stage.show();
    }
}

如果文本发生变化,它将处理保持文本居中的问题。

相关问题