Scribble.java
// Smooth Scribble
// see http://c2.com/~ward/java/Scribble.html
import java.applet.*;
import java.awt.*;
public class Scribble extends Applet implements Runnable {
private double cx = 0, cy = 0; // current x, y
private int fx, fy; // final x, y
private Thread coast = null;
double smooth(double p, double q) {
return (.8 * p) + (.2 * q);
}
void stop() {
if ((coast != null) && coast.isAlive())
coast.stop();
coast = null;
}
boolean mouseDown(Event e, int x, int y) {
this.stop();
cx = x; cy = y;
return true;
}
public synchronized boolean mouseDrag(Event e, int x, int y) {
Graphics g = getGraphics();
double nx = smooth(cx, x); // next x, y
double ny = smooth(cy, y);
g.drawLine((int)cx, (int)cy, (int)nx, (int)ny);
cx = nx; cy = ny;
return true;
}
boolean mouseUp(Event e, int x, int y) {
fx = x; fy = y;
if (coast==null) {
coast = new Thread(this);
coast.start();
}
return true;
}
void run() {
while(true) {
mouseDrag(null, fx, fy);
Thread.sleep(50);
}
}
}
© 1996, Ward Cunningham
All Rights Reserved