Java Reference
In-Depth Information
Example 10•14: ScribblePane4.java (continued)
else super.processMouseMotionEvent(e);
}
public void processKeyEvent(KeyEvent e) {
if ((e.getID() == KeyEvent.KEY_PRESSED) &&
(e.getKeyCode() == KeyEvent.VK_C)) clear();
else super.processKeyEvent(e);
// Give superclass a chance to handle
}
/** These are the coordinates of the the previous mouse position */
protected int last_x, last_y;
/** Remember the specified point */
public void moveto(int x, int y) {
last_x = x;
last_y = y;
}
/** Draw from the last point to this point, then remember new point */
public void lineto(int x, int y) {
getGraphics().drawLine(last_x, last_y, x, y);
moveto(x, y);
}
/** Clear the drawing area, using the component background color */
public void clear() { repaint(); }
}
Custom Events and Event Listeners
Although Swing and the AWT define quite a few event classes and event listener
interfaces, there is no reason you cannot define custom event and listener types of
your own. The class shown in Example 10-15 does exactly that: it defines its own
custom event and listener types using inner classes.
The Swing component set provides a number of ways to allow the user to select
an item from a list of items. You can present such a choice with a JList compo-
nent, a JComboBox component, or a group of cooperating JRadioButton compo-
nents. The APIs for creating, manipulating, and responding to events with these
components differ substantially. Example 10-15 is a listing of an ItemChooser class
that abstracts away the differences between these three presentation types. When
you create an ItemChooser component, you specify the name of the choice being
presented, a list of items to be chosen among, the currently chosen item, and a
presentation type. The presentation type determines how the choice is presented
to the user, but the API you use to work with the ItemChooser component is inde-
pendent of the presentation.
The ItemChooser class includes an inner class named Demo . ItemChooser.Demo has
a main() method that demonstrates the ItemChooser component, as shown in Fig-
ure 10-12. The demo program gets the choice labels from command-line argu-
ments, so you can run it with a command like the following:
% java com.davidflanagan.examples.gui.ItemChooser\$Demo Fourscore and twenty \
years ago
Search WWH ::




Custom Search