import java.awt.*; import javax.swing.*; public class RecursiveTriangles // the book calls this a Sierpinski Triangle (see pages 755-756 for their implementation, mine is shorter and hopefully a little easier to understand) { public static void main(String[] args) { JFrame frame=new JFrame(); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GP p = new GP(); frame.add(p); frame.setVisible(true); } public static class GP extends JPanel { public void paintComponent(Graphics g) { draw(g,250,100,400,400,100,400,6); // start drawing the outermost triangle, 6 is the depth of recursion } public void draw(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int n) // 3 end points x1,y1, x2,y2, x3,y3 { if(n>0) // if we haven't recursed 6 times yet, draw the new triangle at these 3 endpoints { g.drawLine(x1,y1,x2,y2); g.drawLine(x2,y2,x3,y3); g.drawLine(x3,y3,x1,y1); draw(g,x1,y1,(x1+x2)/2,(y1+y2)/2,(x1+x3)/2,(y1+y3)/2,n-1); // and recurse using one of the three points as a base and the other two endpoints to compute midpoints draw(g,(x1+x2)/2,(y1+y2)/2,x2,y2,(x2+x3)/2,(y2+y3)/2,n-1); // our recursive triangle will share one end point and the two new midpoints draw(g,(x1+x3)/2,(y1+y3)/2,(x2+x3)/2,(y2+y3)/2,x3,y3,n-1); } } } }