1

If I want to initialize a local variable in an ActionListener I get this error:

Local variable word defined in an enclosing scope must be final or effectively final.

The code looks something like this:

int number = 0;

anyButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {

        //And here I get the error:
        number++;

    }
});

Do you know how to do it?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • 1
    I'm not going flag this as a duplicate because the question is slightly different, but there are solutions to and reasons behind why this is the case here: [Why are only final variables accessible in anonymous class?](https://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class) – d.j.brown Nov 15 '17 at 18:28
  • Ok! I didn't see that question. I'm sorry! –  Nov 17 '17 at 17:38

1 Answers1

0

You need a mutable thread-safe variable, not a primitive.

Consider replacing that primitive by either a wrapper class (could be your own, or a standard one [e.g. AtomicInteger]) or a single-element array:

final AtomicInteger number = new AtomicInteger();
...
number.getAndIncrement();
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Should the number look like this: `AtomicInteger word = 0;`? That doesn't work... –  Nov 15 '17 at 18:25
  • 1
    @Andy, I provided an example. You can't assign a primitive to a reference type (except for the magic with boxing/unboxing) – Andrew Tobilko Nov 15 '17 at 18:26