分配给每个按钮的操作,在按键的JavaFX中的数组 [英] Assigning an action to each button, in an array of buttons in JavaFX
问题描述
我创建组合框的数组和按钮的JavaFX中的数组。我想指定数组中的每个按钮,做一下相应指标的组合框:
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
这是一个lambda前pression引用的局部变量必须是最终或有效决赛
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?
先谢谢了。
推荐答案
只需创建一个额外的最后一个变量在使用LAMDA:
Just create an extra final variable for use in the lamda:
final ComboBox colorBoxi = colorBox[i];
randomColorBtn[i].setOnAction((ActionEvent event) -> {
colorBoxi.setValue(getRandomPlayerIconColor());
});
这篇关于分配给每个按钮的操作,在按键的JavaFX中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!