Action Listeners and Anonymous Classes

As mentioned before, you have to write Event or Action listeners to give your buttons the ability to actually do anything. These listeners wait for a certain type of event to happen. When such an event happens, the ActionListener executes the code you wrote inside it.

  1. The sending of an event is called firing the event. The object that fires the event is often a GUI component, such as a button that has been clicked.
  2. A listener object performs some action in response to the event. A listener object has methods that specify what will happen when events of various kinds are received by it. These methods are called event handlers.
  3. In Java, every event type has a matching listener interface. For example, MouseEvents implement the MouseListener interface.

This is an example of an action listener. JButtons fire off ActionEvents, so in our example, we need to implement the ActionListener interface. The ActionListener interface consists of a single method. This is the method that we want to be called when the button is pushed.

public void actionPerformed(ActionEvent event)

You will notice that the new keyword is used. This is because you are instantiating an anonymous (or inner) class.

//Register the our object as a listener for the button. 
//Tell the button to call it when the button is pushed.
button.addActionListener
(
	new ActionListener()
	{
		public void actionPerformed(ActionEvent e)
	   {
		  System.out.println("Button clicked.");
	   }
	}
);