1

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 Answer 1

2

Just create an extra final variable for use in the lamda:

final ComboBox colorBoxi = colorBox[i];
randomColorBtn[i].setOnAction((ActionEvent event) -> {
    colorBoxi.setValue(getRandomPlayerIconColor());
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.