Answer:
Registering a listener object establishes a channel of communication between the GUI object and the listener.
Registering the Listener
In this program, the ButtonFrame object is registered
as an ActionListener for its own button.
class ButtonFrame extends JFrame implements ActionListener
{
JButton bChange ;
// constructor
public ButtonFrame()
{
bChange = new JButton("Click Me!");
getContentPane().setLayout( new FlowLayout() );
// register the ButtonFrame object as the listener for the JButton.
bChange.addActionListener( this );
getContentPane().add( bChange );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// listener method required by the interface
public void actionPerformed( ActionEvent evt)
{
. . . . . .
}
}
Examine the statement in the ButtonFrame constructor:
bChange.addActionListener( this );
Here is what it does:
bChangerefers to the button.- The button has a method that that registers a listener for its events:
addActionListener() - The listener is the
ButtonFrameobject.- The word
thisrefers to the object being constructed, the frame.
- The word
- The statement tells the button,
bChange, to run its methodaddActionListener()to register the frame (this) as a listener for button clicks. - Now the frame is listening for
actionEventsfrom the button. - Events will be sent to the
actionPerformed()method
You might think that the ButtonFrame frame 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.