11.3 Listeners and Adapters
|
|
Listeners are used by the AWT to handle various GUI events.
A listener object can be associated with a GUI object, when the
GUI object receives an event it will check if it has a listener
object to handle the event. If it finds a listener object it will
pass the event to the listener for handling.
Listeners are normally interfaces. To use a listener you
must create a class that implements the interface for the type of listener
you need. The class must provide code for the methods declared in the interface.
Then you create an instance of your listener class and associate
it with the GUI object.
Examples of listeners are:
-
WindowListener - Listener that handles window events such as opening and
closing
-
MouseListener - Listener that handle mouse events such as button clicks
-
MouseMotionListener - Listener that handles mouse events for mouse movement
-
KeyListener - Listener for handling keyboard events
-
ActionListener - Listener for handling actions like buttons being pressed
and menus being selected
Adapters are classes that implement listener interfaces but
only provide dummy methods that do nothing. Using an adapter provides
a shortcut for creating listeners since you only have to override
the methods on the adapter that you want to use, the rest have
dummy implementations.