Computer Science 252
Problem Solving with Java
Spring 2014, The College of Saint Rose
ColorfulSpirograph Demo
A working demo of ColorfulSpirograph will appear below. Click inside the applet to interact with it.
ColorfulSpirograph BlueJ Project
Click here to download a BlueJ project for ColorfulSpirograph.
ColorfulSpirograph Source Code
The Java source code for ColorfulSpirograph is below. Click on a file name to download it.
import objectdraw.*; import java.awt.*; import java.util.Random; /* * Example ColorfulSpirograph: adding some randomly chosen * colors to our Spirograph. * * Jim Teresco, Siena College, CSIS 120, Spring 2011 * Modified for CSC 252, The College of Saint Rose, Fall 2013, Spring 2014 * Based on example from Williams College, CSCI 134 * * $Id: ColorfulSpirograph.java 2311 2014-01-23 05:03:17Z terescoj $ */ public class ColorfulSpirograph extends WindowController { // first coordinate of a line segment private Location linesStart; // color of next spriograph private Color currentColor; // random number generator -- created here since there is no // need to construct one each time private Random pickAColor = new Random(); /* * Save the first coordinate of the line, and pick * a new random color. */ public void onMousePress(Location point) { linesStart = point; // since we only need colorNumber within this method, it // is declared as a local variable. // once we use it here to choose currentColor, we no // longer need to remember its value int colorNumber = pickAColor.nextInt(4); switch (colorNumber) { case 0: currentColor = Color.red; break; case 1: currentColor = Color.blue; break; case 2: currentColor = Color.magenta; break; default: currentColor = Color.green; break; } } /* * As the user is dragging draw a line from * initial point where mouse pressed to current point. */ public void onMouseDrag(Location point) { new Line(linesStart, point, canvas).setColor(currentColor); } }