Assigning an action to each button, in an array of buttons in JavaFX

百般思念 提交于 2019-12-13 07:11:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!