如何在for循环中使用每个按钮的lamda表达式制作按钮? [英] How can I make buttons in a for loop with a lamda expression for each?
问题描述
我正在尝试用javafx制作子手游戏.因此,很自然,我没有使用26个单独的按钮,而是尝试使用for循环来创建每个按钮.我将它们放入一个名为Alphabet的ArrayList中,并将其添加到flowPane中.我遇到的麻烦是,当我尝试将每个按钮的操作设置为带有字母参数的函数时,该功能会检查字母是否已使用或是否在单词中.
I'm trying to make a hangman game in javafx. So naturally, instead of making 26 individual buttons, I am trying to use a for loop to create each button. I am putting them into an ArrayList called alphabet and adding them to a flowPane. The trouble I am running into is when I try to set the action of each button to go to a function with the parameter of it's letter that checks to see if the letter has been used or if it is in the word.
所有实例:
ArrayList<Button> alphabet = new ArrayList<Button>();
FlowPane keyboard = new FlowPane();
letterGuess函数(当前为空)
letterGuess function (currently empty)
public void letterGuess(char letter) {
}
launch()函数中的代码:
The code in my launch() function:
char letter;
for(int i=0 ; i<26 ; i++) {
letter = (char) (i+65);
alphabet.add(new Button("" + letter));
keyboard.getChildren().add(alphabet.get(i));
alphabet.get(i).setOnAction(e -> letterGuess(letter));
}
我希望代码能够正确运行,并成功将每个按钮的字母传递给letterGuess().我得到的错误是字母 Alphabet.get(i).setOnAction(e-> letterGuess(字母));该错误表明:在包围范围内定义的局部变量字母必须是最终的或实际上是最终的
I expect the code to run through without an error and successfully pass letter to letterGuess() for each button. The error I get is at letter in alphabet.get(i).setOnAction(e -> letterGuess(letter)); The error says: Local variable letter defined in an enclosing scope must be final or effectively final
推荐答案
问题是您在循环外声明了letter
,因此试图在循环内更改其值.这意味着lambda不能使用它,因为它不是最终版本或有效"最终版本.
The issue is that you're declaring letter
outside the loop and thus trying to change it's value inside the loop. This means the lambda can't use it since it isn't a final or "effectively" final.
您可以通过在循环中将char
声明为新来解决此问题.
You can solve this by declaring the char
as new within the loop.
这是您编写循环的另一种方法,它将很好地工作:
Here is another way you could write the loop which will work fine:
for (int i = 0; i < 26; i++) {
char letter = (char) (i + 65);
Button button = new Button(String.valueOf(letter));
button.setOnAction(event -> letterGuess(letter));
alphabet.add(button);
}
您还可以在循环内将letter
声明为final
,但是在这种情况下没有必要.因为letter
在循环中只分配了一次值,所以有效 final
并且兰巴知道它.
You could also declare letter
as final
within the loop, but it is not necessary in this case. Because letter
is only assigned a value once in the loop, it is effectively final
and the lamba knows it.
这篇关于如何在for循环中使用每个按钮的lamda表达式制作按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!