Why does the addActionListener method need these stages?

600 Views Asked by At
b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ea){
            System.exit(0);
        }
    });

I am learning Java and saw the above code. I can't understand why the addActionlisetner method needs Actionlistener for the argument. Isn't it simpler to just use System.exit(0)?

4

There are 4 best solutions below

0
On BEST ANSWER

You have the the API Java as reference to find the answer of your question.

public void addActionListener(ActionListener l)

Adds an ActionListener to the button.

Parameters:

l - the ActionListener to be added

For example, the concrete class JButton inherited the method addActionListener(ActionListener l) from the class javax.swing.AbstractButton.

When you do :

new ActionListener(){
    public void actionPerformed(ActionEvent ea){
        System.exit(0);
    }
}

You're creating an instance of an anonymous subclass of ActionListener.

ActionListener is an interface made for receiving actions events.

The API says:

The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.

0
On

That's how Java works. You need to pass an instance of an anonymous class to the addActionListener() method (it's a listener after all).

This is how you do things using Java 7 or older. But, using Java 8, you can use a lambda expression to shorten the code (since ActionListener is a functional interface):

// You can do this
b.addActionListener((ActionEvent) ae -> System.exit(0));
// or this
b.addActionListener((ActionEvent) ae -> {
    System.exit(0);
});
// or even better, this
b.addActionListener(ae -> System.exit(0));
0
On

The argument of addActionListener specifies an instance of the event handler class as listener of a component (in this case 'b') Passing an instance of the anonymouos class 'ActionListener' or an instance of your own class (b.actionListener(this)), both will work.

0
On

Basically, The actionPerformed() method in ActionListener class is called when you press a button.

You cannot have b.addActionListener(System.exit(0)); because System.exit(0) is a method. In Java, you can't pass methods as arguments but you can pass classes.