To a listener object. But our program does not have one, yet.
In analogy to window events, you would expect that there would be a ButtonAdapter class used as a base class for button listener objects. But there isn't. You need to define the complete class of a button listener from scratch.
A button listener class must
implement the ActionListener
interface.
ActionListener
is an interface (not a class)
that contains the
single method:
public void actionPerformed( ActionEvent evt) ;The
ActionEvent
parameter it expects
is an Event
object that represents an event (a button click).
It contains information that can be used
in responding to the event.
Since ActionListener
is an interface,
you use it with a class that will implement the
actionPerformed()
method.
It is common to implement the interface in the same class that contains the button(s):
public class buttonDemo2 extends JFrame implements ActionListener { JButton bChange; // constructor for buttonDemo2 buttonDemo2() { getContentPane().setLayout( new FlowLayout() ); bChange = new JButton("Click Me!"); getContentPane().add( bChange ); } // listener method implemented for interface public void actionPerformed( ActionEvent evt) { . . . . . . } public static void main ( String[] args ) { ButtonDemo2 frm = new ButtonDemo2(); . . . . . } }
This is a slightly different approach than was used with the
WindowEvent
of the previous chapter,
where the WindowAdapter
class was extended to
define a spearate class for the listener.