import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; import javax.swing.JPanel; /** * A JPanel on which to draw a Sierpinski Triangle. * * @author David Mutchler and YOUR-NAME-HERE. * Created October 18, 2008. */ public class SierpinskiPanel extends JPanel { private final int panelWidth; private int levelOfDetail; /** * Sets the size of the panel to the given value * and sets the initial level of detail for the Sierpinski Triangle to 1. * * @param panelWidth Width of this panel */ public SierpinskiPanel(int panelWidth) { this.panelWidth = panelWidth; this.levelOfDetail = 1; int panelHeight = (int) (this.panelWidth * Math.sqrt(3.0) / 2.0); this.setPreferredSize(new Dimension(this.panelWidth, panelHeight)); } /** * Increases the level of detail for the Sierpinski Triangle by 1. */ public void increaseLevelOfDetail() { ++ this.levelOfDetail; } /** * Decreases the level of detail for the Sierpinski Triangle by 1. */ public void decreaseLevelOfDetail() { if (this.levelOfDetail > 0) { -- this.levelOfDetail; } } /** * Draws the Sierpinski triangle at the current level of detail. * * @param graphics Graphics object on which to draw */ @Override public void paintComponent(Graphics graphics) { super.paintComponent(graphics); int lengthOfSide = this.panelWidth; int heightOfTriangle = (int) (lengthOfSide * Math.sqrt(3) / 2.0); Polygon triangle = new Polygon(); triangle.addPoint(lengthOfSide / 2, 0); triangle.addPoint( 0, heightOfTriangle); triangle.addPoint(lengthOfSide, heightOfTriangle); graphics.setColor(Color.blue); graphics.fillPolygon(triangle); this.drawSierpinski(graphics, this.levelOfDetail); } /** * Draws the Sierpinski Triangle (recursively). * STUDENTS: add additional parameters to this method as needed. * * @param graphics Graphics object on which to draw * @param levelOfDetail Level of detail (bigger => more triangles) */ private void drawSierpinski(Graphics graphics, int levelOfDetail) { // TODO: Write this method. } }