0

I am trying to apply a method to an array of arrays through a for loop.

Unfortunately where I have inserted my array of arrays inside the checkGuess method, I am getting the error 'Local variable x defined in an enclosing scope must be final or effectively final'. I'm a little new to Java so I'm not sure what I'm doing wrong... any help would be greatly appreciated.

for(int x = 0; x < columns.length; x++){
columns[x][y].addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event) {
        checkGuess(columns[x][y]);
    }
});

    if(x>4 && y<5){
        y++;
        x=-1;       
    }
}

Additional info:

The array of arrays contains JButtons. The method checkGuess() takes a JButton as an argument as so:

checkGuess(JButton guess){
}
user3124181
  • 782
  • 9
  • 24
  • possible duplicate. check this [answer](http://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class) – Amit.rk3 Jun 03 '15 at 16:48

2 Answers2

0

ActionListener is an inner anonymous class and it doesn't know what 'x' is when it tries to read it when passing the array of arrays to the function checkGuess().

Untested, but this might work:

for(int x = 0; x < columns.length; x++){
columns[x][y].addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event) {
        checkGuess(this);
    }
});

    if(x>4 && y<5){
        y++;
        x=-1;       
    }
}

If not, you would need to find out how to pass x into the class.

I believe "this" will reference the parent of the class, which should be 'columns[x][y]. I could be wrong though.

AzNjoE
  • 733
  • 3
  • 9
  • 18
0

In Java, variables that are used in an anonymous class must be final (or in Java 8, effectively final - essentially the same thing, just without the explicit final modifier). As for why this is, Jon Skeet has a very nice answer to this here.

One method of correcting your code is simply to assign x to a final reference, as shown below:

for (int x = 0; x < columns.length; x++) {
    final int copy = x;

    columns[x][y].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            checkGuess(columns[copy][y]);
        }
    });
}
Community
  • 1
  • 1