java:是否可以为按钮数组设置 lambda 表达式是一个 for 循环?如果是这样怎么办? [英] java: Is it possible to set a lambda expression for an array of Buttons is a for loop? If so how?

查看:22
本文介绍了java:是否可以为按钮数组设置 lambda 表达式是一个 for 循环?如果是这样怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够做这样的事情:

I want to be able to do something like this:

for(i = 0; i < 10; i++) {
    //if any button in the array is pressed, disable it.
    button[i].setOnAction( ae -> { button[i].setDisable(true) } );
}

但是,我收到一条错误消息,指出从 lambda 表达式引用的局部变量必须是最终的或有效的最终变量".我怎么还能像上面的代码那样做(如果可能的话)?如果做不到,应该怎么做才能得到类似的结果?

However, I get a error saying "local variables referenced from a lambda expression must be final or effectively final". How might I still do something like the code above (if it is even possible)? If it can't be done, what should be done instead to get a similar result?

推荐答案

正如错误消息所说,从 lambda 表达式引用的局部变量必须是最终的或有效的最终的(有效的最终"意味着编译器可以为您使其成为最终的).

As the error message says, local variables referenced from a lambda expression must be final or effectively final ("effectively final" meaning the compiler can make it final for you).

简单的解决方法:

for(i = 0; i < 10; i++) {
    final int ii = i;
    button[i].setOnAction( ae -> { button[ii].setDisable(true) } );
}

这篇关于java:是否可以为按钮数组设置 lambda 表达式是一个 for 循环?如果是这样怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆