-1

I am trying to access in an inner class (actionListener) a variable that changes value in the main class. I can't make it final, because it changes values before the actionListener triggered.

Have anyone met the same problem?

Thank you

public class MyClass{
    private int counter = 0;

    public void myMethod(){
        //read from file
        //counter = number of lines of the file read

        JButton button = new JButton ("My button");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("lines = " +counter);
            }
        });
    }
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
Vasileios
  • 85
  • 1
  • 2
  • 11

2 Answers2

1

Make the variable non-local, an instance field, and then your problem is solved.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

You can simply pass that variable to your inner class:

public class Outer {

    private E outerValue;

    public void someMethod() {
        Inner inner = new Inner(outerValue);
        // later
        outerValue = newValue;
    }

    public class Inner {
        private final E innerValue;
        public Inner(E value) {
            this.innerValue = value;
        }
        // + other methods
    }
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118