-4

can you explain me what does the "local variable referenced from an inner class must be final or effectively final" error means, and why i'm getting it even after declaring my variables involved as final.

here is my code:

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);
                    }

                });
            }
        }
    }
}

i'm getting the error in this line

labels[i][j].setBorder(border);

what i'm trying to do is changing the labels color borders when mouseEvent (clicked , pressed or dragged), and i need to use the i,j variables inside the mouseClicked method.

Lyes
  • 400
  • 5
  • 19

1 Answers1

5

after all the feedbacks I got I finally managed to find a solution that suits me,the key was to substitute the i,j variables with two other final variables, like that I could use them inside the mouseClicked method

   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());
            }       });
     }
}
}
Lyes
  • 400
  • 5
  • 19
  • 1
    If you wanted the variables for another reason than referring to the same element of `labels`, your question should state that, because it changes the solution. – Andy Turner Nov 03 '18 at 18:23