首页 > 解决方案 > 如何修复从内部类引用的局部变量必须是最终或有效的最终错误

问题描述

你能解释一下“从内部类引用的局部变量必须是最终的或有效的最终”错误是什么意思,以及为什么即使在将涉及的变量声明为最终变量之后我也会得到它。

这是我的代码:

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 变量。

标签: javamouseevent

解决方案


在得到所有反馈之后,我终于找到了适合我的解决方案,关键是将 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());
            }       });
     }
}
}

推荐阅读