【问题标题】:Accessing Variable within JButton ActionListener在 JButton ActionListener 中访问变量
【发布时间】:2023-03-10 05:09:01
【问题描述】:

这似乎是一个非常简单的问题,但我很难弄清楚如何处理它。

示例场景:

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

我真的不知道该去哪里。

【问题讨论】:

  • 请说明您需要做什么和不能做什么。

标签: java scope jbutton actionlistener


【解决方案1】:

如果您将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 范围内。这就是为什么你不能直接在你的动作监听器中看到变量“数字”,你必须访问你所在的场景实例。这可以通过 Scenario.this

【讨论】:

  • ClassName.this?这到底是做什么的?
  • 我怀疑数字是否可以是私有的,或者它必须受到保护/公开
  • 啊,谢谢;这很有意义。从来没有真正想过这个。
【解决方案2】:

最快的解决方案是将number 声明为static,并使用您的类名来引用它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2020-11-01
    相关资源
    最近更新 更多