Hello,

I'm trying to finish a program that produces a Sierpinski Carpet fractal, but the squares that the program prints are appearing over each other. The program should print the overlapping squares underneath each other, however. I'm not sure how to fix the problem, but I know it has something to do with the placement of the final fillRect line.

Thoughts? Thank you.


Code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
public class Sierpinski {
 public static final int PANEL_SIZE = 243;
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  DrawingPanel panel = new DrawingPanel(PANEL_SIZE, PANEL_SIZE);
  Graphics g = panel.getGraphics();
  int width = PANEL_SIZE / 3;
  int height = PANEL_SIZE / 3;
  int x = PANEL_SIZE / 3;
  int y = PANEL_SIZE / 3;
  System.out.print("Please enter an integer: ");
  int limit = input.nextInt();
  draw(limit, g, x, y, width, height);
 }

 public static void draw(int limit, Graphics g, int x, int y, int width,int height) {
  Random randNum = new Random();
  int numberRed = randNum.nextInt(255) + 1;
  int numberBlue = randNum.nextInt(255) + 1;
  int numberGreen = randNum.nextInt(255) + 1;
  Color randColor = new Color(numberRed, numberGreen, numberBlue);
  g.setColor(randColor);
  if (limit <= 0) {
   return;
  }
  if (limit == 1) {
   g.fillRect(x, y, width, height);
  }
  else {
   g.fillRect(x, y, width, height);
   width /= 3;
   height /= 3;
   // separating into 3x3 grid
   int x1 = x - 2 * width;
   int y1 = y - 2 * height;
   int x2 = x + width;
   int y2 = y + height;
   int x3 = x + 4 * width;
   int y3 = y + 4 * height;
   draw(limit - 1, g, x1, y1, width, height);
   draw(limit - 1, g, x2, y1, width, height);
   draw(limit - 1, g, x3, y1, width, height);
   draw(limit - 1, g, x1, y2, width, height);
   draw(limit - 1, g, x1, y3, width, height);
   draw(limit - 1, g, x2, y3, width, height);
   draw(limit - 1, g, x2, y2, width, height);
   draw(limit - 1, g, x3, y3, width, height);
   draw(limit - 1, g, x3, y2, width, height);
  }
 }
}