img
The WindowListener Interface
This interface defines seven methods. The windowActivated( ) and windowDeactivated( )
methods are invoked when a window is activated or deactivated, respectively. If a window
is iconified, the windowIconified( ) method is called. When a window is deiconified,
the windowDeiconified( ) method is called. When a window is opened or closed, the
windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( )
method is called when a window is being closed. The general forms of these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Using the Delegation Event Model
Now that you have learned the theory behind the delegation event model and have had an
overview of its various components, it is time to see it in practice. Using the delegation event
model is actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type
of event desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient
for the event notifications.
Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement
all of the interfaces that are required to receive these events.
To see how the delegation model works in practice, we will look at examples that handle
two commonly used event generators: the mouse and keyboard.
Handling Mouse Events
To handle mouse events, you must implement the MouseListener and the MouseMotionListener
interfaces. (You may also want to implement MouseWheelListener, but we won't be doing
so, here.) The following applet demonstrates the process. It displays the current coordinates
of the mouse in the applet's status window. Each time a button is pressed, the word "Down"
is displayed at the location of the mouse pointer. Each time the button is released, the word
"Up" is shown. If a button is clicked, the message "Mouse clicked" is displayed in the upper-
left corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the upper-left
corner of the applet display area. When dragging the mouse, a * is shown, which tracks with
the mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store
the location of the mouse when a mouse pressed, released, or dragged event occurs. These
coordinates are then used by paint( ) to display output at the point of these occurrences.
// Demonstrate the mouse event handlers.
import java.awt.*;
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home