Java Reference
In-Depth Information
Note
Not all these events are used by AWT. For example,
MenuDragMouseEvent
is Swing-specific. Also, events can be classified as high-
levelorlow-level.A
high-level event
resultsfromalow-levelinteractionwiththeGUI.
Forexample,anactioneventoriginatesfromakeypressoramouseclick.Incontrast,
keyboard-oriented and mouse-oriented events are
low-level events
.
Components that generate events are known as
event sources
. As events occur,
AWTEvent
subclassinstancesarecreatedtodescribethem.Eachinstanceispostedto
an
event queue
andsubsequently
dispatched
(sent)totheappropriateeventlistenersthat
werepreviouslyregisteredwiththeeventsource.Eventlistenersrespondtotheseevents
in some way, which typically involves updating the GUI.
Aneventlistenerisregisteredwithacomponentbycallingthecomponentclass'sap-
propriate
add
x
Listener()
methodonthecomponentinstance,where
x
isreplaced
with an event class name without the
Event
suffix. For example, you would register
an action listener with a button by calling
Button
's
void addActionListen-
er(ActionListener al)
method.
ActionListener
isaninterfaceinthe
java.awt.event
package.AWTcalls
its
void
ae)
method with the
Ac-
actionPerformed(ActionEvent
tionEvent
object when an action event occurs.
The following example registers an action listener with the previously created Yes
button:
btnYes.addActionListener(new ActionListener()
{
public
void
actionPer-
formed(ActionEvent ae)
{
System.out.println("yes was
clicked");
}
});
When the user clicks the Yes button, AWT calls
actionPerformed()
with an
ActionEvent
objectasthismethod'sargument.Thelistenerrespondsbyoutputtinga
message on the standard output device.
Button
alsodeclaresa
void removeActionListener(ActionListener
al)
methodforunregisteringthepreviouslyregisteredactionlisteneridentifiedas
al
.