1

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

示例场景:

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

我真的不知道该去哪里。

4

2 回答 2

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

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

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

于 2013-10-07T15:18:13.683 回答
2

最快的解决方案是声明numberstatic,并使用您的类名引用它。

或者,您可以创建一个类,并将其implements ActionListener传递给它的构造函数。numbertext

于 2013-10-07T15:19:01.950 回答