Java Reference
In-Depth Information
Example 10•11: ScribblePane1.java (continued)
// A method from the MouseListener interface. Invoked when the
// user presses a mouse button.
public void mousePressed(MouseEvent e) {
last_x = e.getX(); // remember the coordinates of the click
last_y = e.getY();
}
// A method from the MouseMotionListener interface. Invoked when the
// user drags the mouse with a button pressed.
public void mouseDragged(MouseEvent e) {
int x = e.getX();
// Get the current mouse position
int y = e.getY();
// Draw a line from the saved coordinates to the current position
this.getGraphics().drawLine(last_x, last_y, x, y);
last_x = x;
// Remember the current position
last_y = y;
}
// The other, unused methods of the MouseListener interface.
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
// The other, unused, method of the MouseMotionListener interface.
public void mouseMoved(MouseEvent e) {}
}
More Mouse Events
Example 10-12 shows a listing of
ScribblePane2.java
. which is much like
Scrib-
blePane1
except that it uses anonymous inner classes to define its event listeners.
This is a common GUI programming idiom in Java, and, in fact, it was one of the
primary reasons that anonymous inner classes were added to the language. Note
that the inner classes subclass event adapter classes, rather than implement the
event listeners directly; this means that unused methods don't have to be imple-
mented.
ScribblePane2
also includes a
KeyListener
that clears the scribble when the user
types the C key and defines a
color
property (with
setColor()
and
getColor()
as
its property accessor methods) that specifies the color in which to scribble. Recall
that the
ShowComponent
program allows you to specify property values. It under-
stands colors specified using hexadecimal RGB notation, so to use this example to
scribble with blue lines, you can use a command like this:
% java com.davidflanagan.examples.gui.ShowComponent \
com.davidflanagan.examples.gui.ScribblePane2 color=#0000ff
A final point to note about this example is that the scribbling functionality has
been cleaned up and placed into
moveto()
,
lineto()
, and
clear()
methods. This
allows the methods to be invoked by other components and allows the compo-
nent to be subclassed more cleanly.