Java Reference
In-Depth Information
Low-Level Event Handling
As we just discussed, graphical user interfaces do not usually concern themselves
with the details of low-level mouse and keyboard events. Instead, they use prede-
fined components to interpret these events for them. By the same token, prede-
fined components that handle frequent mouse and keyboard events do not usually
use the high-level event listener API to handle these low-level events.
Example 10-14 shows a listing of ScribblePane4.java , a final reimplementation of
our scribble component. This version does not use event listeners at all, but
instead overrides the processMouseEvent() , processMouseMotionEvent() , and
processKeyEvent() methods defined by its java.awt.Component superclass. * Event
objects are passed to these methods directly, without any requirement to register
event listeners. What is required, however, is that the constructor call
enableEvents() to specify the kinds of events in which it is interested. If the con-
structor does not do this, the system may not deliver events of those types, and
the various event processing methods may never be invoked. Note that the event
processing methods invoke the superclass' implementation for any events they do
not handle themselves. This allows the superclass to dispatch these events to any
listener objects that may have been registered.
Example 10•14: ScribblePane4.java
package com.davidflanagan.examples.gui;
import javax.swing.*;
// For JPanel component
import java.awt.*;
// For Graphics object
import java.awt.event.*;
// For Event and Listener objects
/**
* Another scribble class. This one overrides the low-level event processing
* methods of the component instead of registering event listeners.
**/
public class ScribblePane4 extends JPanel {
public ScribblePane4() {
// Give the component a preferred size
setPreferredSize(new Dimension(450,200));
// Tell the system what kind of events the component is interested in
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.KEY_EVENT_MASK);
}
public void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
moveto(e.getX(), e.getY());
requestFocus();
}
else super.processMouseEvent(e); // pass unhandled events to superclass
}
public void processMouseMotionEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_DRAGGED) lineto(e.getX(), e.getY());
* This same technique can be used with the processFocusEvent() , processComponentEvent() , and pro-
cessWindowEvent methods of Component .
Search WWH ::




Custom Search