java - 如何修复从内部类引用的局部变量必须是最终或有效的最终错误
问题描述
你能解释一下“从内部类引用的局部变量必须是最终的或有效的最终”错误是什么意思,以及为什么即使在将涉及的变量声明为最终变量之后我也会得到它。
这是我的代码:
public class FenetreJeu extends JFrame {
final Echiquier e = new Echiquier();
FenetreJeu fj;
final public JLabel[][] labels = new JLabel[8][8];
Color couleur = new Color(51, 102, 0);
final Border border = BorderFactory.createLineBorder(Color.RED, 3);
public void moves() {
for (int i = 0; i <= 7; i++) {
for (int j = 0; j <= 7; j++) {
labels[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent ee) {
labels[i][j].setBorder(border);
}
});
}
}
}
}
我在这一行得到了错误
labels[i][j].setBorder(border);
我要做的是在 mouseEvent (单击、按下或拖动)时更改标签颜色边框,并且我需要在 mouseClicked 方法中使用 i,j 变量。
解决方案
在得到所有反馈之后,我终于找到了适合我的解决方案,关键是将 i,j 变量替换为其他两个最终变量,就像我可以在 mouseClicked 方法中使用它们一样
public void moves(){
for (int i = 0; i<=7;i++){
for ( int j=0 ; j <= 7 ; j++){
final int k = i;
final int l = j;
labels[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent ee) {
labels[k][l].setBorder(border);
System.out.println("the case holding the "+e.cases[k][l].getPiece().getType());
} });
}
}
}
推荐阅读
- c++ - 使用抽象多态类型初始化 C++ 2D shared_ptr 数组
- javascript - 为使用 preventDefault() 设置父级的嵌套菜单启用最后一个子链接单击;
- ios - 从服务器获取 CKC 后 iOS FairPlay 视频不播放
- c++ - 在 C++ 模板中将变量作为参数传递
- angular - 延迟加载模块中 Angular Material 日期选择器的语言切换
- android - 尝试将 SearchView 添加到我的 appcompat 活动时出现 Nullpointerexception
- typescript - TypeScript 递归函数返回未定义
- laravel - vue-for循环内每个元素的不同数据
- reactjs - 如何在 Redux 和 React.js 中对异步多个请求使用 Loader
- javascript - 没有for循环的数组过滤器上的Javascript多个条件