Search code examples
javauser-interfacejavafxgame-developmentgridpane

How do I get X and Y Coordinates of different rows and columns in a gridpane?


I'm currently making a game board and want to be able to move pieces from one tile to another. I'm trying to do this by getting the centerX and centerY of each tile as the user click on it, which would then allow me to move my pieces based off of those values.

Here is what I tried:

gameBoard.setOnMouseClicked(evt -> {
        Node target = evt.getPickResult().getIntersectedNode();

        if (target != gameBoard) {
            Bounds bounds = target.getBoundsInParent();
            System.out.println("bounds = " + bounds);
            System.out.println("centerX = " + (bounds.getMinX() + bounds.getWidth()/2));
            System.out.println("centerY = " + (bounds.getMinY() + bounds.getHeight()/2));
        }
});

However centerX = and centerY = only print out 25.0, no matter the grid row/column I click on. Any advice?


Solution

  • The problem is probably caused by target.getBoundsInParent() this gives you the clicked element bounds in relation to its parent.

    The reason why you got the

    centerX = 25.0

    and

    centerY = 25.0

    for all the cells is because, if your grid cells are uniform, clicking any cells will give you same dimension and its relative position with its parent.

    try to convert the local coordinates to your scene coordinates.

    gameBoard.setOnMouseClicked(evt -> {
        Node target = evt.getPickResult().getIntersectedNode();
    
        if (target != gameBoard) {
            Bounds bounds = target.getBoundsInParent();
            Point2D pointInScene = target.localToScene(bounds.getMinX() + bounds.getWidth() / 2, bounds.getMinY() + bounds.getHeight() / 2);
    
            System.out.println("bounds = " + bounds);
            System.out.println("centerX in Scene = " + pointInScene.getX());
            System.out.println("centerY in Scene = " + pointInScene.getY());
        }
    });