Kar
Kar

Reputation: 23

JavaFx Can't obtain stackPane position on Scene

I have a class which extends StackPane. Another one which makes a 20x20 2d Array of this class. I then translated their position somewhere on the scene. Right now, I can't obtain the position of a cell relative on the scene. I tried Bounds, Point2D.zero and getMin..

                cell.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        System.out.println("mouse click detected! " + mouseEvent.getSource());
//                      boundsInScene = cell.localToScene(cell.getLayoutBounds());
//                      System.out.println("Cell width: " + boundsInScene.getMinX());
//                      System.out.println("Cell height: " + boundsInScene.getMinY());
//                      cell.localToScene(Point2D.ZERO);
                        int x = (int) cell.getTranslateX();
                        int y = (int) cell.getTranslateY();
                        System.out.println("X: " + x + "y :" + y);

                    }
                });

Part of my code:

private Parent createContent() {
    root = new Pane();
    root.setPrefSize(640, 480);
    for (int col = 0; col < y_Tiles; col++) {
        for (int row = 0; row < x_Tiles; row++) {
            cell = new Cell(row, col);
            grid_Array[row][col] = cell;

            cell.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {});


            root.getChildren().add(cell);
        }
    }

    return root;
}

Bounds is resturning me 480 and 400. Another thing is that all cells return the same output for any of the methods I tried. Any idea how to cell the position of a cell on the scene? PS:Sorry for bad english. Not native language

Upvotes: 1

Views: 176

Answers (1)

jewelsea
jewelsea

Reputation: 159556

You shouldn't be using translateX/Y to set the location of your items. translateX/Y should just be used for temporary movements of an item, such as a bounce effect or a transition. layoutX/Y should be used to set the location of items. Normally layoutX/Y will be set automatically by a layout pane. If you aren't using a layout pane and are manually performing the layout in an unmanaged parent (such as a Pane or a Group), then you can manually set the layoutX/Y values as needed (relocate will do this).

Once you switch to setting the layout values rather than the translate values, then you determine the location of any node in a scene using the localToScene function.

Bounds boundsInScene = node.localToScene(node.getLayoutBounds());

Upvotes: 3

Related Questions