Java Reference
In-Depth Information
Event Handling Methods
Description
processEvent(AWTEvent e)
This method is called first for any events that
are enabled for the component. If you
implement this method, and fail to call the
base class method, none of the methods for
specific groups of events will be called.
processFocusEvent(FocusEvent e)
This method will be called for focus events, if
they are enabled for the component.
processKeyEvent(KeyEvent e)
This method will be called for key events, if
they are enabled for the component.
processMouseEvent(MouseEvent e)
This method will be called for mouse button
events, if they are enabled for the
component.
processMouseMotionEvent(
MouseEvent e)
This method will be called for mouse move
and drag events, if they are enabled for the
component.
processMouseWheelEvent(
MouseWheelEvent e)
This method will be called for mouse wheel
rotation events, if they are enabled for the
component.
All the event-handling methods for a component are
protected
methods that have a return type of
void
. The default behavior implemented by these methods is to dispatch the events to any listeners
registered for the component. If you don't call the base class method when you override these methods
after your code has executed, this behavior will be lost.
Although it was very convenient to handle the window closing event in the
SketchFrame
class by implementing
processWindowEvent()
, as a general rule
you should use listeners to handle events. Using listeners is the recommended
approach to handling events in the majority of circumstances, since separating the
event handling from the object that originated the event results in a simpler code
structure that is easier to understand, and is less error prone. We will change this in
the Sketcher code a little later in this chapter.
Low-level Event Listeners
To create a class that defines an event listener, your class must implement a listener interface. All event
listener interfaces extend the interface
java.util.EventListener
. This interface doesn't declare any
methods though - it's just used to identify an interface as being an event listener interface. It also allows a
variable of type
EventListener
to be used for storing a reference to any kind of event listener object.
There are a very large number of event listener interfaces. We'll look at just eight at this point that are
concerned with low-level events. These declare the following methods: