«^»
7.1. Use of interfaces for GUI callbacks

Perhaps a Java programmer's first use of an interface occurs with handling the events of a GUI. For example, suppose a window (JFrame) has a button (JButton):

final JFrame tJFrame = new JFrame("some title");
final JButton tJButton = new JButton("click here");
final Container tContentPane = tJFrame.getContentPane();
tContentPane.add(tJButton, BorderLayout.CENTER);
tJFrame.pack():
tJFrame.setVisible(true);

If the program has to react to a click of the button, the program has to create an object and register it as a listener:

final JButtonListener tJButtonListener = new JButtonListener();
tJButton.addActionListener(tJButtonListener);

Here we have created an object of a class called JButtonListener and passed tJButtonListener as the argument of the addActionListener method. The documentation of addActionListener states that its parameter is of the interface type ActionListener. So JButtonListener must be a class that implements the ActionListener interface:

public class JButtonListener implements ActionListener
{
   ...
}

Looking again at the documentation of the ActionListener interface, you will see that this interface is simply:

public interface ActionListener
{
   public void actionPerformed(ActionEvent pActionEvent);
}

So this means that JButtonListener could be something like:

public class JButtonListener implements ActionListener
{
   public void actionPerformed(final ActionEvent pActionEvent)
   {
      final Date tDate = new Date();
      System.out.println(tDate);
   }
}