I'm working on a Minesweeper game using JavaFX:

My GridPane is made of ImageViews, and I'm trying to find a way to figure out the column and row indexes of the image that was clicked on the GridPane. I have this code currently:
gameGrid.setOnMouseClicked(event -> //gameGrid is my GridPane
{
Node source = (Node)event.getSource();
int columnIndex = GridPane.getColumnIndex(source);
System.out.println(columnIndex);
int rowIndex = GridPane.getRowIndex(source);
if(event.getButton()== MouseButton.PRIMARY)
game.newRevealCell(columnIndex,rowIndex);
else if(event.getButton()==MouseButton.SECONDARY)
game.getGrid()[columnIndex][rowIndex].setFlagged(true);
//game.getGrid is a 2D array containing the game cells
});
However, the methods getColumnIndex and getRowIndex are returning null. What am I doing wrong?
Starting from this example, the variation below fills a
GridPanewithNxNinstances ofButton, adding each to aList<Button>. The methodgetGridButton()shows how to obtain a button reference efficiently based on its grid coordinates, and the action listener shows that the clicked and found buttons are identical.How does each grid button know its own location on the grid? Each one gets its own instance of an anonymous class—the button's event handler—that has access to the row and column parameters passed to
createGridButton(). These parameters are effectively final; in contrast, the original example using an earlier version of Java had to make the parameters explicitly final.While this approach obtains the row and column of any
Nodein the grid, aButtonorToggleButtonmay be more convenient in this context. In particular, you can usesetGraphic()withContentDisplay.GRAPHIC_ONLYto get the desired appearance.As an aside, the
GridPanemethodsgetColumnIndexandgetRowIndexreturnnullas they refer to the child's index constraints, only if set, as illustrated here.For models using a two dimensional array, also consider a
List<List<Button>>, illustrated below: