Search code examples
javabuttonthisactionlistenerframes

What parameters are used when .addActionListener() is called?


I've been learning quite a lot in Java recently but something has been really bugging me. I learned / was taught how to use ActionListeners when the program involves a constuctor, for example,

public class test extends JFrame implements ActionListener {
JButton button;

public test 
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
    test testprogram = new test();
    test.setVisible(true);
}
@Override
    public void actionPerformed(ActionEvent clickevent) {
    if (clickevent.GetSource() == button) { 
      //DoSomething
    }
}

Solution

  • It can be anything which implements ActionListener.

    You might want to consider not making your JFrame implement ActionListener: this means that

    1. It is part of the class' interface that it implements actionPerformed; but you probably don't want other classes to call that directly.
    2. You can only implement it "once", so you end up having to have conditional logic to determine what the source of the event was, and then handle it appropriately.

    The alternative is to create a button-specific action listener:

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent clickevent) {
        // Don't need to check if it is from button, nothing else
        // could have created the event.
      }
    });
    

    and remove implements ActionListener from the test class.