在同一个 class 中为三个按钮实现 ActionListener

implement ActionListener in the same class for three buttons

我在一个框架中有三个按钮,其中两个我想用来编辑一个字符串,它是主要 Class (Lab2TestDrive) 中的一个包 public 成员,类似于

 public class Lab2TestDrive{
...
String cale;

public static main void(String[] args){
    JButton button1.. button2.. button3..

}

我可以在 Lab2TestDrive 上实现一个 ActionListener,并覆盖其中的 actionPerformed(...) 方法吗?但是,如果我这样做,我不知道如何知道哪个按钮触发了 actionPerformed 方法。

我知道我可以单独制作一个 class,

public class ButtonListener implements ActionListener {
    JButton button;
    ButtonListener(JButton button){
        this.button = button;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(button.getText().equals("Save")){

        };

    }
}

但是我不知道如何访问 "cale" 变量:(

首先:你不应该让你的 ActionEvent 被称为 arg0

然后:从技术上讲,您可以一次完成所有操作 class。您的 ActionEvent 参数有一个名为 getSource() 的方法,它将为您提供触发事件的按钮。

理论上,您还可以创建第三个 class 来存储您的 cale 变量,并将对该 class 的引用作为您的侦听器构造函数的参数。

然而,这似乎很不直观。

您还可以将 Lab2TestDrive 对象的引用提供给 Listener 的构造函数,然后从 actionPerformed.[=16= 中调用 class 的方法]

说实话,none 这些选项确实让我印象深刻,因为它们是很好的编码实践,但它们都应该有效。