Java Reference
In-Depth Information
listeners. The AWT
Button
class and the Swing
JButton
class, for example,
include the method
addActionListener (ActionListener al)
(Technically, in the case of
JButton
, the
addActionListener()
method is
inherited from the
AbstractButton
class.)
Any class, not just graphics components, can implement the
ActionLis-
tener
interface. For example, an applet class can implement
ActionListener
and then pass the
this
reference to the
addActionListener()
method. Other
components provide similar “add listener” methods to add listeners for the events
they generate. For example, the
JPanel
class includes
addMouseListener (MouseListener ml)
and the
TextField
class includes the method
addTextListener (TextListener tl).
7.2.2 Event information
So you implement a listener interface and provide an implementation of the
method (for example,
actionPerformed()
) that receives an event object.
What can you do with the event? Typically you will need to obtain essential
information from the event such as the identity of the object that sent it. If, for
example, it was generated by a mouse, you can extract the screen coordinates of
the cursor location when the event occurred.
The root event class is
java.util.EventObject
but its subclass,
java.awt.AWTEvent
,isthe primary class for events in the AWT system.
There are various subclasses of
AWTEvent
in the
java.awt.event
package
such as
ActionEvent
,
ItemEvent
, and
TextEvent
. These are used to pro-
vide information on specific types of events such as those from buttons, menu
items, and text fields.
It is possible that many different components could have generated the event
sent to
actionPerformed()
.For example, a user interface might have several
buttons that could have sent an
ActionEvent
. The method
getSource()
in
EventObject
returns an
Object
reference to the component that generated the
event. A test with the
instanceof
operator will indicate the type of component
that generated the event. You can also compare the reference to a list of component
references to determine the specific object that sent the event.
We will give several examples of events and event handling in the following
sections. See also Chapter 7 in the Web Course for additional information and
demonstration applets.
Search WWH ::
Custom Search