Event Handling
Event Handling
Event Handling
• The classes that represent events are at the core of Java’s event handling
mechanism. The most widely used events are those defined by the AWT
and those defined by Swing.
• At the root of the Java event class hierarchy is EventObject, which is in
java.util. It is the superclass for all events. Its one constructor is shown
here: EventObject(Object src)
Here, src is the object that generates this event.
• EventObject contains two methods: getSource( ) and toString( ).
• The getSource( ) method returns the source of the event. Its general form
is shown here: Object getSource( )
• As expected, toString( ) returns the string equivalent of the event.
• The class AWTEvent, defined within the java.awt package, is a
subclass of EventObject.
• It is the superclass (either directly or indirectly) of all AWT-based
events used by the delegation event model.
• Its getID( ) method can be used to determine the type of the event.
• The signature of this method is shown here:
int getID( )
• The package java.awt.event defines many types of events that are
generated by various user interface elements.
The ActionEvent Class
• An ActionEvent is generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
• The ActionEvent class defines four integer constants that can be used
to identify any modifiers associated with an action event: ALT_MASK,
CTRL_MASK, META_MASK, and SHIFT_MASK.
• In addition, there is an integer constant, ACTION_PERFORMED, which
can be used to identify action events.
• ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
• Here, src is a reference to the object that generated this event.
• The type of the event is specified by type, and its command string is cmd.
• The argument modifiers indicates which modifier keys (ALT, CTRL, META,
and/or SHIFT) were pressed when the event was generated.
• The when parameter specifies when the event occurred.
• You can obtain the command name for the invoking ActionEvent object by
using the getActionCommand( ) method, shown here:
String getActionCommand( )
• For example, when a button is pressed, an action event is generated
that has a command name equal to the label on that button.
• The getModifiers( ) method returns a value that indicates which
modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the
event was generated.
• Its form is shown here: int getModifiers( )
• The method getWhen( ) returns the time at which the event took
place. This is called the event’s timestamp.
• The getWhen( ) method is shown here: long getWhen( )
The AdjustmentEvent Class