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)
?
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.