JavaFX StackPane显示不正确的(X,Y)协调

问题描述 投票:0回答:2

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

码:

@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布局/平移未显示。我也使用过: rec1.setLayoutX(230),但这并没有改变任何东西。

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

java javafx javafx-8 coordinates
2个回答
2
投票

要打印出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);
        }
    }

1
投票

如果你尝试rec1.setX(100)它将显示为[矩形[x = 100.0,y = 0.0]。 rec1.setY()也是如此。看看有关setX()setTranslateX()setLayoutX()的文档。

© www.soinside.com 2019 - 2024. All rights reserved.