Mouse Input: Java Doodle

Here’s a simple applet that lets you doodle with the mouse on an applet.

import java.applet.Applet;
import java.awt.*;
import java.util.Vector;

public class JavaDoodle extends Applet {

Vector points = new Vector();

public void paint(Graphics g) {

int x1, y1, x2, y2;
Point tempPoint;

if (points.size() > 1) {
tempPoint = (Point) points.elementAt(0);
x1 = tempPoint.x;
y1 = tempPoint.y;
for (int i = 1; i < points.size(); i++) {
tempPoint = (Point) points.elementAt(i);
x2 = tempPoint.x;
y2 = tempPoint.y;
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
} // end for
} // end if
}

public boolean mouseDown(Event e, int x, int y) {
points.addElement(new Point(x, y));
return true;
}

public boolean mouseDrag(Event e, int x, int y) {
points.addElement(new Point(x, y));
repaint();
return true;
}

public boolean mouseUp(Event e, int x, int y) {
points.addElement(new Point(x, y));
repaint();
return true;
}

}

Exercises

1. Revise the applet so that it doesn’t draw a line between the point where the mouse button was released and the point where it was pressed again.

Comments are closed.