JavaFX StackPane showing incorrect (X,Y) Coordination

0

I am trying to print all the nodes in the StackPane. I am required to get X,Y coordinates and height and width of the nodes (all Rectangls). However, it shows (0,0) for the X,Y coordinates even though I have specifically chosen other than it.

Code:

@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());
}

Output:

[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]]

As you can see from the output above. The height and width works but the X and Y layout/translation is not showing. I have also used: rec1.setLayoutX(230) but this did not change anything.

What is the problem? And how can I fix this? Thanks.

java
javafx
javafx-8
coordinates
asked on Stack Overflow Mar 2, 2019 by dali Sarib

2 Answers

2

To printout information other than included in Node.toSring tailor the printout to your needs. For example:

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);
        }
    }
answered on Stack Overflow Mar 2, 2019 by c0der
1

If you try rec1.setX(100) it will show it as [Rectangle[x=100.0, y=0.0]. Same for rec1.setY(). Have a look on the docs about setX(), setTranslateX(), setLayoutX().

answered on Stack Overflow Mar 2, 2019 by Stef

User contributions licensed under CC BY-SA 3.0