We want a button object to notify our program that it has been pressed. The usual way two objects communicate is for one to call a method in the other, something like this:
class JButton
{
...
Program program;
...
program.notify();
...
}
class Program
{
notify()
{
// do something
}
}
The problem with this is that the JButton class is a
pre-compiled library class, so there is no way it can know about our
Program class. Instead, the button object notifies an
ActionListener object. In fact, ActionListener
is an interface rather than a class, and the method in it which the button
calls is actionPerformed, like this:
class JButton
{
...
ActionListener listener;
...
listener.actionPerformed(event);
...
}
class Program implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
...
}
}
For a button to notify our program, we have to do several things. First, we have to tell the button which object wants to listen:
MyListener listener = ...;
button.addActionListener(listener);
Then we have to define a class which implements the ActionListener interface by providing the right
method
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// do something
}
}