import objectdraw.*; /** * Create nested squares recursively. */ public class NestedSquaresV2 { private static final double SQUARE_SPACING = 20; private static final double SMALLEST_SIDE_SIZE = 50; private FramedRect outerSquare; // the outermost square private NestedSquaresV2 restOfSquares; // the rest of the squares // create the nested squares at (upperLeftX, upperLeftY) with spacing // squareSpacing and an outermost square that has side of length sideSize. public NestedSquaresV2(double upperLeftX, double upperLeftY, double sideSize, DrawingCanvas canvas) { // always draw the outer square outerSquare = new FramedRect(upperLeftX, upperLeftY, sideSize, sideSize, canvas); // if the sideSize is still greater than the smallest side size, // draw the rest recursively if (sideSize > SMALLEST_SIDE_SIZE) { sideSize -= SQUARE_SPACING * 2; upperLeftX += SQUARE_SPACING; upperLeftY += SQUARE_SPACING; restOfSquares = new NestedSquaresV2(upperLeftX, upperLeftY, sideSize, canvas); } } // centers the squares on the given point public void centerOnPoint(Location point) { outerSquare.moveTo(point.getX() - outerSquare.getWidth()/2, point.getY() - outerSquare.getHeight()/2); if (restOfSquares != null) { restOfSquares.centerOnPoint(point); } } // move nested squares by indicated offsets public void move(double xOffset, double yOffset) { outerSquare.move(xOffset, yOffset); if (restOfSquares != null) { restOfSquares.move(xOffset, yOffset); } } // count the nunmber of squares public int countSquares() { if (restOfSquares == null) { // base case: only 1 square return 1; } return 1 + restOfSquares.countSquares(); } // checks if the Location is in the NestedSquares object public boolean contains(Location point) { return outerSquare.contains(point); } }