Source Code:
import objectdraw.*;
import java.awt.*;
// illustrates random number generation and the use of the
// Color class.
// When mouse is dragged, draws a line following the mouse's path. The
// color of the line is randomly selected from four options.
public class RandomColors extends WindowController{
private Location lastPoint; // location where mouse was last pressed
private Color currentColor; // current color for scribbling
private int colorNumber; // random int generated for color selection
// a random number generator that generates random numbers
// between 1 and 4 (inclusive)
RandomIntGenerator pickAColor = new RandomIntGenerator(1,4);
// remember point of press
// generate a random color with which lines will be drawn
public void onMousePress(Location point) {
lastPoint = point;
colorNumber = pickAColor.nextValue();
if (colorNumber == 1) {
currentColor = Color.red;
}
else if ( colorNumber == 2) {
currentColor = Color.blue;
}
else if ( colorNumber == 3 ) {
currentColor = Color.magenta;
}
else {
currentColor = Color.green;
}
}
// draws a line with the random color selected at the time of mouse press
public void onMouseDrag(Location point) {
new Line( lastPoint, point, canvas).setColor( currentColor);
lastPoint = point;
}
}