Issue
I am making a game-board which requires a grid of buttons. I have a method where I can put in the width and height of the board and draw it like this:
for (int i = 0; i < gameBoardWidth; i++) {
for (int j = 0; j < gameBoardHeight; j++) {
gameLayout.add(tiles[j], j, i);
}
}
The code above works perfectly fine but the problem is, I have an array of buttons. the size of the array is equal to the width * height, Each button within that array needs to have a unique ID incremented from 1 to n. Previously I made the board with this method
for(int i = 0; i < gameBoardDimension; i++) {
tiles[i] = new Button("");
tiles[i].setMinSize(gameButtonWidth, gameButtonHeight);
tiles[i].setId(Integer.toString(i));
Button btn = tiles[i];
btn.setOnAction(e -> {
turn = 1;
int ID = Integer.parseInt(btn.getId());
setMove(ID, turn, btn);
setAIMove();
});
}
But with the method above it is impossible to show them in a grid. How can I show the buttons in a grid so every button in the array has an ID of 1 to n with n being the size of the array?
Solution
Create an id as row (i) times width plus column (j) (plus 1 to start from 1 instead of 0) in the loop
for (int i = 0; i < gameBoardWidth; i++) {
for (int j = 0; j < gameBoardHeight; j++) {
Button b = new Button("");
//... other stuff for button
int id = i * gameBoardWidth + j + 1;
b.setId(Integer.toString(id));
//...
}
}
Answered By - Joakim Danielson