JavaFX - How do I know where a button in a GridPane exists?

I have a fxml file which has GridPane and I wanna locate buttons in each square of the GridPane. Then I wanna show an image on a button which is just clicked. However, when a button is clicked and a method in controller is called, there seems to be no information about the location of the clicked button. Without this, I can't know what square to show an image. How can I solve this problem?

I'm using JavaFX ScneBuilder2.0. I've already tried to make a lot of methods the number of which corresponds with the number of square in GridPane. Obviously it resulted in producing too long source file and I gave up to do that.

Here is part of controller class.

package client;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;

public class GomokuController implements Initializable{
    @FXML private GridPane gomokuBoard;
    @FXML private Button[][] put_stone_button = new Button[15][15];

    @FXML public void put_stone(){
      //called by pushing a button in the GridPane
      //I wanna know in which square the pushed button locates.

1 answer

  • answered 2019-05-15 03:32 Zephyr

    You should just be able to call the GridPane.getRowIndex() and GridPane.getColumnIndex() methods and pass in the Button that was clicked.

    However, you will need to somehow pass the Button to your put_stone() method. In the example below, I'm passing a reference to your Button to the method when the button is clicked:

    put_stone_button[0].setOnAction(event -> put_stone(put_stone_button[0])
    public void put_stone(Button button){
      int row = GridPane.getRowIndex(button);
      int column = GridPane.getColumnIndex(button);

    You will likely need to adapt this solution to your project as your implementation is not clear in the code you posted.

    Side Note: Please learn the Java naming conventions and stick to them.