Reputation: 7
I want all of the buttons on my grid to change from blank to X to O and then back to blank every time they are clicked. it currently only works for the first element in the array as the values of I and j are both 0. Do I need a loop similar to where I initialise the buttons?
I though the two nested for loops were what I need to add, however I have tried this and it has worked.
Any suggestions?
Upvotes: 0
Views: 134
Reputation: 82461
You use final fields i
and j
are used to set the event handler. If you want all the buttons to use handle the click the same way, you need to register the event handler to every button.
Since you can only access effectively final variables inside the loop you need to make a final copy of the loop variables or simply declare a local variable for the Button
.
final List<String> values = Arrays.asList("", "X", "O");
for(int i=0; i<btn.length; i++){
for(int j=0; j<btn.length;j++){
final Button button = new Button("");
button.setOnAction(event -> {
int valueIndex = values.indexOf(button.getText());
button.setText(values.get((valueIndex+1) % values.size()));
});
// Initializing 2D buttons with values i,j
btn[i][j] = button;
button.setPrefSize(35, 40);
gridPane.add(button, i, j);
// button.setDisable(false);
}
}
Upvotes: 2
Reputation: 2468
You can define a single event handler and assign it to all your buttons in your loop
EventHandler<ActionEvent> eventHandler = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Button button = (Button) event.getSource();
switch (button.getText()) {
case "":
button.setText("X");
break;
case "X":
button.setText("O");
break;
default:
button.setText("");
break;
}
}
};
//Two FOR loops used for creating 2D array of buttons with values i,j
for(int i=0; i<btn.length; i++){
for(int j=0; j<btn.length;j++){
// Initializing 2D buttons with values i,j
btn[i][j] = new Button();
btn[i][j].setPrefSize(35, 40);
gridPane.add(btn[i][j], i, j);
btn[i][j].setText("");
btn[i][j].setDisable(false);
btn[i][j].setOnAction(eventHandler);
}
}
Upvotes: 0