// demonstrates use of recursion graphically import java.awt.*; import javax.swing.JApplet; public class LineRecursion extends JApplet { private static final long serialVersionUID = 1L; private final int APPLET_WIDTH = 640; private final int APPLET_HEIGHT = 320; private final int MIN_HEIGHT = 15; // smallest bar height private final int BAR_WIDTH = 5; private static final Color[ ] choices = new Color[ ] {Color.blue, Color.red, Color.orange, Color.cyan}; /* * 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 drawLines(Graphics page, int loc, int colorChoice, int height) { page.setColor(choices[colorChoice]); page.fillRect(loc, 0, BAR_WIDTH, height); if (height > MIN_HEIGHT) { drawLines(page, loc - height/2, nextColor(colorChoice), height/2); drawLines(page, loc + height/2, nextColor(colorChoice), height/2); } } /* * perform the initial call to the drawPictures method */ public void paint (Graphics page) { drawLines(page, APPLET_WIDTH/2, 0, APPLET_WIDTH/2); } }