Computer Science 252
Problem Solving with Java

Fall 2013, The College of Saint Rose

NestedSquaresRec Demo

A working demo of NestedSquaresRec will appear below. Click inside the applet to interact with it.



NestedSquaresRec BlueJ Project

Click here to download a BlueJ project for NestedSquaresRec.


NestedSquaresRec Source Code

The Java source code for NestedSquaresRec is below. Click on a file name to download it.


NestedSquaresRec.java

import objectdraw.*;
import java.awt.*;

/*
 * Example NestedSquaresRec: a recursive implementation of an
 * object consisting of nested squares.
 *
 * Jim Teresco, The College of Saint Rose, CSC 252, Fall 2013
 *
 * $Id: NestedSquaresRec.java 2227 2013-10-24 03:37:54Z terescoj $
 */

public class NestedSquaresRec {

    private static final int SIZE_CHANGE = 4;
    
    // a recursive implementation: we draw nested squares
    // by creating the outermost square, then calling
    // THIS CONSTRUCTOR to draw the rest, which are really
    // just another set of nested squares, just a little bit
    // smaller and a little bit down and to the right.
    public NestedSquaresRec(double x, double y, int size, DrawingCanvas c) {
        
        if (size > 0) {
            // draw one
            new FramedRect(x, y, size, size, c);
            // draw the rest
            new NestedSquaresRec(x + SIZE_CHANGE/2, y+SIZE_CHANGE/2,
                size - SIZE_CHANGE, c);
        }
    }
}

DrawNestedSquares.java

import objectdraw.*;
import java.awt.*;

/*
 * Example NestedSquaresLoop: draw some nested squares objects
 * when the mouse is pressed
 *
 * Jim Teresco, The College of Saint Rose, CSC 252, Fall 2013
 *
 * $Id: DrawNestedSquares.java 2227 2013-10-24 03:37:54Z terescoj $
 */

public class DrawNestedSquares extends WindowController {
   
    public void onMousePress(Location point) {
	
        new NestedSquaresRec(point.getX(), point.getY(), 100, canvas);
    }
}