如何在java中访问内部类中的变量而不成为最终变量?

如何在java中访问内部类中的变量而不成为最终变量?,java,class,variables,Java,Class,Variables,我试图在一个内部类(actionListener)中访问一个变量,该变量会更改主类中的值。我无法将其设置为最终设置,因为它会在触发actionListener之前更改值 有人遇到过同样的问题吗 多谢各位 public class MyClass{ private int counter = 0; public void myMethod(){ //read from file //counter = number of lines of the

我试图在一个内部类(actionListener)中访问一个变量,该变量会更改主类中的值。我无法将其设置为最终设置,因为它会在触发actionListener之前更改值

有人遇到过同样的问题吗

多谢各位

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

您只需将该变量传递给内部类:

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

将变量设为非本地,作为一个实例字段,然后您的问题就解决了。

请显示一些示例代码。仅供参考,请编辑您的问题,并在问题中发布代码,而不是评论。很难读。谢谢。您发布的代码没有您刚才描述的问题,因为计数器是一个实例字段,而不是局部变量。让我重申一下,你发布的代码有什么问题?它起作用了。请澄清。看看答案。我想他指的是匿名课程