0

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.

//GomokuController.java
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 Answers1

2

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.

Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • Thank you so much! And I need to cast the Object instance which I got by "event.getSource()" into Node type, right? – yuki amezaki May 15 '19 at 03:43
  • Yes, that is correct. I did change my example, however, to pass a reference to the button itself. But if you use the `ActionEvent` parameter, you would need to cast the source to your node type, correct. – Zephyr May 15 '19 at 03:44
  • Thank you for another way of coding. And I hit on another solution. That is, creating an anonymous class and define an event method when I create a Button instance. However, I think it's not so good idea from memory usage viewpoint(In my solution, every Button has its anonymous class). If possible, would you tell me other defects in my idea? – yuki amezaki May 15 '19 at 04:00