Search code examples
javaswingjbuttonactionlistener

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

 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? But if I do that, I don't know how I would be able to know which button triggered the actionPerformed method.

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 :(


Solution

  • First: You should not let your ActionEvent be called 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.

    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.

    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.

    Truth be told, none of those options really strikes me as great coding practice, but they should all work.