Registering a listener object establishes a channel of communication between the GUI object and the listener.
The container (a ButtonDemo2 object) can be registered
as a listener for any of the components it contains.
When a ButtonDemo2 object is constructed we will register
it 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( WindowConstants.EXIT_ON_CLOSE );
}
// listener method required by the interface
public void actionPerformed( ActionEvent evt)
{
. . . . . .
}
}
Examine the statement:
bChange.addActionListener( this );
This statement is executed when a ButtonFrame object is constructed.
bChange refers to the button.addActionListener()
ButtonFrame object.
this refers to the object being constructed,
the frame.bChange, to run its method
addActionListener() to register the frame (this)
as a listener
for button clicks.actionEvents from the button.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.