问题
I've created an array of ComboBoxes and an array of buttons in JavaFX. I'd like to assign each button of the array, to do something to the ComboBox of the corresponding index:
for(int i = 0; i < 6; i++) {
colorBox[i] = new ComboBox();
colorBox[i].getItems().addAll("Blue", "Orange", "Green", "Yellow", "White", "Red");
randomColorBtn[i] = new Button("Random color");
randomColorBtn[i].setOnAction((ActionEvent event) -> {
colorBox[i].setValue(getRandomPlayerIconColor());
});
}
So that whenever you click the Random button, the corresponding ComboBox gets set to a random color. However, when I try to do it like this, I get the error that
local variables referenced from a lambda expression must be final or effectively final
I get that the error originates from me using the variable i, but how can I get around this issue?
Thanks in advance.
回答1:
Just create an extra final variable for use in the lamda:
final ComboBox colorBoxi = colorBox[i];
randomColorBtn[i].setOnAction((ActionEvent event) -> {
colorBoxi.setValue(getRandomPlayerIconColor());
});
来源:https://stackoverflow.com/questions/33323804/assigning-an-action-to-each-button-in-an-array-of-buttons-in-javafx