简体   繁体   English

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

[英]implement ActionListener in the same class for three buttons

I have three buttons in a frame, two of which I want to edit a String with, which is a package public member in the main Class (Lab2TestDrive), something like 我在一个框架中有三个按钮,我想用其中的两个按钮编辑一个String,它是主类(Lab2TestDrive)中的程序包公共成员,类似于

 public class Lab2TestDrive{
...
String cale;

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

}

Can I implement an ActionListener on Lab2TestDrive, and override the actionPerformed(...) method in there? 我可以在Lab2TestDrive上实现ActionListener并在其中重写actionPerformed(...)方法吗? But if I do that, I don't know how I would be able to know which button triggered the actionPerformed method. 但是,如果这样做,我不知道如何知道哪个按钮触发了actionPerformed方法。

I know I could make a separate 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")){

        };

    }
}

But then I don't know how I could access the "cale" variable :( 但是然后我不知道如何访问“ cale”变量:(

First: You should not let your ActionEvent be called arg0 . 首先:您不应让您的ActionEvent称为arg0

Then: You can technically do it all in one class. 然后:从技术上讲,您可以在一堂课中完成所有操作。 Your ActionEvent parameter has a method called getSource() which will get you the button that fired the event. 您的ActionEvent参数具有一个名为getSource()的方法,该方法将为您触发事件的按钮。

In theory, you could also create a third class storing your cale variable and give a reference to that class as a parameter to the constructor of your listener. 从理论上讲,您还可以创建一个第三类来存储您的cale变量,并将对该类的引用作为参数提供给侦听器的构造函数。

However, that seems very unintuitive. 但是,这似乎非常不直观。

You could also give a reference to your Lab2TestDrive object to the constructor of your Listener and then call a method from that class from within your actionPerformed . 您还可以Lab2TestDrive对象的引用提供给侦听器的构造函数,然后在actionPerformed从该类调用方法。

Truth be told, none of those options really strikes me as great coding practice, but they should all work. 实话实说,所有这些选项都没有让我成为出色的编码实践,但是它们应该都能奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM