A good answer might be:

Registering a listener object establishes a channel of communication between the GUI object and the listener.

Registering the Listener

The container (a buttonDemo object) can be registered as a listener for any of the components it contains. When a buttonDemo object is constructed we will register it as an ActionListener for its button.

public class buttonDemo extends Frame implements ActionListener
{
  Button bChange = new Button("Click Me!"); // construct a Button

  buttonDemo()                           // constructor for buttonDemo
  {
    setLayout( new FlowLayout() );       // choose the layout manager 
    bChange.addActionListener( this );   // register the buttonDemo object 
                                         // as the listener for its Button.
    add( bChange );                      // add the button to the container
  }
  
  public void actionPerformed( ActionEvent evt)
  {
      . . . . .
  }

  public static void main ( String[] args )
  {
      . . . . .
  }
}

Examine carefully the statement:

    bChange.addActionListener( this );
This statement is executed when a buttonDemo object is constructed.
  1. bChange refers to the Button object.
  2. The Button object has a method that is used to register a listener for it: addActionListener()
  3. The listener we wish to register is the buttonDemo object.
    • The word this is used to mean the object being constructed.
  4. The statement tells the Button (bChange) to run its method (addActionListener()) to register the frame (this) as a listener for button clicks.
  5. Now the Frame is listening for actionEvents from the Button it contains.
You might think that this is stupid, that the buttonDemo object should automatically be registered as the listener for all of the GUI components it contains. But this would eliminate the flexibility that is needed for more complicated GUI applications.

QUESTION 8:

You want the program to do something when the button is clicked. Where should the code to "do something" go?      

Click Here after you have answered the question