import java.awt.*; import javax.swing.*; public class Triangles { public static void main(String[] args) { JFrame frame=new JFrame(); frame.setSize(500,500); TrianglePanel panel=new TrianglePanel(); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private static class TrianglePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); draw(g,250,100,100,400,400,400,8); // start our recursion with 1 triangle from 250,100 to 100,400 to 400,400 and size of 8 } public void draw(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int c) { g.drawLine(x1,y1,x2,y2); // draw a new "inner" triangle g.drawLine(x2,y2,x3,y3); g.drawLine(x3,y3,x1,y1); int xn1=(x1+x2)/2; // obtain the midpoints for each of the 3 lines int xn2=(x2+x3)/2; int xn3=(x1+x3)/2; int yn1=(y1+y2)/2; int yn2=(y2+y3)/2; int yn3=(y1+y3)/2; if(c>0) // if we haven't recursed 7 times yet, recurse using the midpoints of this triangle for the next one draw(g,xn1,yn1,xn2,yn2,xn3,yn3,c-1); } } }