JavaFX StackPane 显示不正确的 (X,Y) 坐标

JavaFX StackPane showing incorrect (X,Y) Coordination

我正在尝试打印 StackPane 中的所有节点。 我需要获取节点的 X、Y 坐标以及高度和宽度(所有 Rectangls)。 但是,它显示 X、Y 坐标为 (0,0),即使我特别选择了它以外的坐标。

代码:

@Override
public void start(Stage primaryStage) {
    Rectangle rec1 = new Rectangle();
    rec1.setTranslateX(230);
    rec1.setTranslateY(230);
    rec1.setWidth(50);
    rec1.setHeight(50);

    Rectangle rec2 = new Rectangle();
    rec2.setTranslateX(150);
    rec2.setTranslateY(150);
    rec2.setWidth(75);
    rec2.setHeight(75);

    StackPane root = new StackPane();
    root.getChildren().add(rec1);
    root.getChildren().add(rec2);

    Scene scene = new Scene(root, 1280, 720);

    primaryStage.setTitle("Shapes");
    primaryStage.setScene(scene);
    primaryStage.show();

    System.out.println(root.getChildren());
}

输出:

[Rectangle[x=0.0, y=0.0, width=50.0, height=50.0, fill=0x000000ff], Rectangle[x=0.0, y=0.0, width=75.0, height=75.0, fill=0x000000ff]]

从上面的输出可以看出。高度和宽度有效,但 X 和 Y layout/translation 未显示。我也用过: rec1.setLayoutX(230) 但这并没有改变任何东西。

有什么问题? 我该如何解决这个问题? 谢谢

如果您尝试 rec1.setX(100),它将显示为 [Rectangle[x=100.0, y=0.0]。 rec1.setY() 也一样。查看有关 setX(), setTranslateX(), setLayoutX().

的文档

要打印 Node.toSring 中未包含的信息,请根据您的需要定制打印输出。例如:

print(root.getChildren());
private void print(ObservableList<Node> children) {
        for(Node child: children){
            double width = child.getBoundsInLocal().getWidth();
            Object height = child.getBoundsInLocal().getHeight();
            double x = child.getTranslateX();
            double y = child.getTranslateY();
            System.out.println("trans x - y: " + x + " - "+y  + " width - height: " + width +" - "+ height);
        }
    }