0
int a = 0 ;

btnNormal.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e3)
    {
        a = 2;
    }
});

I want to do this, but the eclipse says: Local variable a defined in an enclosing scope must be final or effectively final. If I change to a final int nothing happens. What is the solution? How can I change the int in the actionListener?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
copy14
  • 3
  • 3
  • 2
    Does this answer your question? [Problems with local variable scope. How to solve it?](https://stackoverflow.com/questions/25894509/problems-with-local-variable-scope-how-to-solve-it) – OH GOD SPIDERS Aug 12 '21 at 14:43
  • Counter-question: why do you want to set that variable? I.e. what are your intentions? – Turing85 Aug 12 '21 at 14:44

1 Answers1

0

You could use an array as a workaround to your problem. Like this:

int[] a = {0};

btnNormal.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e3)
    {
        a[0] = 2;
    }
});

Or the AtomicInteger class:

final AtomicInteger a = new AtomicInteger(0);
btnNormal.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e3)
    {
        a.set(2);
    }
});
Renis1235
  • 4,116
  • 3
  • 15
  • 27