Java Reference
In-Depth Information
7.2.3 Button events
Buttons provide the most common event generating components in user inter-
faces. (See the
JButton
and other button classes in the Swing hierarchy in
Figure 6.2.) Clicking on a button should initiate some action and in fact the term
action
is used in the names for the button event handling machinery. A button
maintains a list of objects that implement the
ActionListener
interface. When
the button is pressed, it invokes the
actionPerformed()
method for all of the
ActionListener
instances in its list. To include an
ActionListener
in its
list, you invoke the button's
addActionListener(ActionListener al)
method.
ActionListener
classes must provide an implementation of the method
void actionPerformed (ActionEvent ae)
Yo u use this method to code for the particular operation required when the
user clicks the button. An
ActionEvent
object is passed as the parameter of
actionPerformed()
and from it you can extract information about the event
such as which button initiated the event.
We mentioned above the
getSource()
method inherited from
EventOb-
ject
that can identify what object sent the event. With buttons you can also use
the method
getActionCommand()
in
ActionEvent
to identify the button
that sent the event. This method returns either the text string displayed on the but-
ton or a string set directly with the
setActionCommand()
method (inherited
from
AbstractButton
class).
The
PlainButtonApplet
program below implements the
ActionLis-
tener
interface and so provides an
actionPerformed()
method. We create
two instances of
JButton
and then add the applet to the buttons'
ActionLis-
tener
lists with the statements:
buttonA.addActionListener (this);
buttonB.addActionListener (this);
Here the
“
this
„
reference refers to the applet instance.
Each time the GUI button is clicked with the mouse button, the GUI button's
actionPerformed()
method is invoked. From the
ActionEvent
we obtain
the identity of the button via the
getActionCommand()
method and decide
Figure 7.1
The
PlainButton
applet running illustrates event handling for buttons.
Each click on a button sends a message to the status bar.
Search WWH ::
Custom Search