// demonstrates use of recursion graphically import java.awt.*; import javax.swing.JApplet; public class PiledSquares extends JApplet { private static final long serialVersionUID = 1L; private final int APPLET_WIDTH = 320; private final int APPLET_HEIGHT = 320; private final int MIN = 20; // smallest picture size private static final Color[ ] choices = new Color[ ] {Color.red, Color.blue, Color.yellow}; /* * sets the window size */ public void init( ) { setSize(APPLET_WIDTH, APPLET_HEIGHT); } /* * returns next color in sequence */ public int nextColor(int index) { index++; if (index >= choices.length) { index = 0; } return index; } /* * draws a rectangle, then calls itself recursively */ public void drawPictures(int size, Graphics page, int colorChoice) { page.setColor(choices[colorChoice]); page.fillRect(size/2, size/2, size/2, size/2); colorChoice = nextColor(colorChoice); page.setColor(choices[colorChoice]); page.fillRect(size/4, size/2 + size/4, size/4, size/4); page.fillRect(size/2 + size/4, size/4, size/4, size/4); page.fillRect(size/2 + size/4, size/2 + size/4, size/4, size/4); if (size > MIN) { drawPictures(size/2, page, colorChoice); } } /* * perform the initial call to the drawPictures method */ public void paint (Graphics page) { drawPictures(APPLET_WIDTH, page, 0); } }