Registering a listener object establishes a channel of communication between the GUI object and the listener.
class ButtonFrame2 extends JFrame implements ActionListener
{
JButton bChange ;
// constructor
public ButtonFrame2()
{
bChange = new JButton("Click Me!");
setLayout( new FlowLayout() );
// register the ButtonFrame object as the listener for the JButton.
bChange.addActionListener( this );
add( bChange );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// listener method required by the interface
public void actionPerformed( ActionEvent evt)
{
. . . . . .
}
}
In this program, the ButtonFrame2
object is registered
as an ActionListener
for its own button.
Here is how this is done:
bChange
refers to the button.bChange.addActionListener( this )
registers a listener for its events.
ButtonFrame2
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 ButtonFrame2
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.