Reputation: 61
I am making a simple chess game with javaFX. I create my chessboard by using an fxml file, and i used a gridPane with a button inside each cell. When the user press a button, i want to get the column and rown index of the pressed button. Is there a way to do this? I was thinking about using a function like this, but it is not working.
private void buttonClicked(MouseEvent event) {
Button btn = (Button) event.getSource();
String nome = btn.getId();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(nome);
alert.setHeaderText(null);
alert.setContentText(nome);
alert.showAndWait();
}
I also made the same function trying to print the id of the parent, but is still not working. On the fxml file, the call to this function is the following:
<AnchorPane prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
<children>
<Button layoutX="14.0" layoutY="19.0" mnemonicParsing="false" onAction="#buttonClicked" prefHeight="63.0" prefWidth="94.0" styleClass="blackButton" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
Upvotes: 1
Views: 1945
Reputation: 2129
You can't pass parameter to the buttonclicked Handler.
But you can retrieve row/column coordinate with :
AnchorPane cellAnchorPane = (AnchorPane) btn.getParent();
int row = GridPane.getRowIndex(cellAnchorPane);
int col = GridPane.getColumnIndex(cellAnchorPane);
By the way I don't know what you are trying to achieve but I Don't think the button need to be Inside an AnchorPane. And create a chessBoard in fxml instead of code will be really repetitive
Look at this sample app. You can create an handler and pass those parameter
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
GridPane gridpane = new GridPane();
Scene scene = new Scene(gridpane, 400, 400);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
Button b = new Button("cell " + i + " - " + j);
final int col = i;
final int row = j;
b.setOnAction(a -> buttonClicked(col, row));
gridpane.add(new AnchorPane(b), i, j);
}
}
primaryStage.setScene(scene);
primaryStage.show();
}
private void buttonClicked(int col, int row) {
System.out.println("button : " + col + " -" + row + " pressed");
}
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 1