在JButton ActionListener中访问变量

Mau*_*kye 1 java scope jbutton actionlistener

这似乎是一个非常简单的问题,但我在弄清楚如何处理它时遇到了很多麻烦.

示例场景:

    final int number = 0;

    JFrame frame = new JFrame();
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    frame.setSize(400, 400); 

    final JTextArea text = new JTextArea();
    frame.add(text, BorderLayout.NORTH);

    JButton button = new JButton(number + ""); 
    button.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
        number++; // Error is on this line
        text.setText(number + "");
    }});
    frame.add(button, BorderLayout.SOUTH);
Run Code Online (Sandbox Code Playgroud)

我真的不知道该往哪里去.

ang*_*rro 5

如果您声明number为final,则无法修改其值.您必须删除final修改器.

然后,您可以通过以下方式访问该变量:

public class Scenario {
    private int number;

    public Scenario() {
        JButton button = new JButton(number + "");
        button.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent arg0) { 
                Scenario.this.number++;
                text.setText(Scenario.this.number + "");
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

符号"ClassName.this"允许您访问您所在类的对象.

在第一次使用"数字"时保持注意, - new JButton(number)- ,您可以直接访问号码,因为您处于场景范围内.但是当您在ActionListener中使用它时,您处于ActionListener范围而不是Scenario范围.这就是为什么你不能直接在动作监听器中看到变量"number"的原因,你必须访问你所在的Scenario实例.这可以通过Scenario.this来完成.