I\'m new to JavaFX (Java for that matter) and I want to be able to click a GridPane and have it display my room attributes in a side-panel(or to console at this point). I\'ve ma
Since you register the event handler at the GridPane
, the source of the event is the GridPane
itself. You did not set the row/column index for the GridPane
and it wouldn't contain any useful information.
In this case you need to get the node that was actually clicked from the MouseEvent
:
public void clickGrid(javafx.scene.input.MouseEvent event) {
Node clickedNode = event.getPickResult().getIntersectedNode();
if (clickedNode != gridmane) {
// click on descendant node
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}
}
In this case the code works like this since the children of your GridPane
don't have children of their own that could be the intersected node.
If you want to add children that could have children of their own you need to go up through the node hierarchy until you find a child of the GridPane
:
if (clickedNode != gridmane) {
// click on descendant node
Node parent = clickedNode.getParent();
while (parent != gridmane) {
clickedNode = parent;
parent = clickedNode.getParent();
}
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}