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.
- bChange refers to the Button object.
- The Button object has a method that is used to register a listener for it: addActionListener()
- The listener we wish to register is the buttonDemo object.
- The word this is used to mean the object being constructed.
- The statement tells the Button (bChange) to run its method
(addActionListener()) to register the frame (this) as a listener
for button clicks.
- 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.
|