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?
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
and
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.