Java Reference
In-Depth Information
EXAMPLE 12-10
The program in this example shows how to handle the mouse-dragged event. You can
handle the mouse moved event similarly. These events are handled by the
interface
MouseMotionListener
, which contains the methods
mouseDragged
and
mouseMoved
,
which, in turn, are used to handle the mouse-dragged and mouse-moved events,
respectively.
The program starts with some colored dots. If you drag a dot using the mouse, the dot
turns into a line. This way, you can ''freehand draw'' different pictures. What is really
happening is that we created small circle objects. The program contains the method
selected
to check whether or not the mouse is on a circle. If you drag a circle, the
method
mouseDragged
is invoked and it paints a new circle. The sequence of circles
gives the impression of drawing a line. The complete program listing follows:
import
javax.swing.*;
import
java.awt.event.*;
import
java.applet.*;
import
java.awt.*;
public class
FreeDrawApplet
extends
JApplet
implements
MouseMotionListener
{
//instance variables
ColorCircle[] myGraph;
final int
NUM_CIRCLES = 7;
final int
WIDTH = 400;
final int
HEIGHT = 400;
public class
ColorCircle
{
private int
x;
private int
y;
public void
setX(
int
iNewX)
{
x = iNewX;
}
public void
setY(
int
iNewY)
{
y = iNewY;
}
public void
paint (Graphics g)
{
g.fillOval(x - 10, y - 10, 20, 20);
}
Search WWH ::
Custom Search