Ye-Young Jeon Ye-Young Jeon - 3 months ago 21
Java Question

Why does the addActionListener method need these stages?

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ea){

I am learning Java and saw the above code.
I can't understand why the
method needs
for the argument.
Isn't it simpler to just use


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.


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){

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.