import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KochPanel extends JPanel { public KochPanel() { setPreferredSize(new Dimension(600, 600)); setBackground(Color.WHITE); } // Display the snowflake public void paintComponent(Graphics aPen) { super.paintComponent(aPen); drawSnowflake(300,300,200,aPen); } // This code does all the actual drawing public void drawSnowflake(int cx, int cy, int size, Graphics aPen) { int px = cx + (int)(size * Math.cos(Math.toRadians(90))); int py = cy + (int)(size * Math.sin(Math.toRadians(90 + 180))); int qx = cx + (int)(size * Math.cos(Math.toRadians(-30))); int qy = cy + (int)(size * Math.sin(Math.toRadians(-30+180))); int rx = cx + (int)(size * Math.cos(Math.toRadians(210))); int ry = cy + (int)(size * Math.sin(Math.toRadians(210+180))); drawKochEdge(px, py, qx, qy, -60, aPen); drawKochEdge(qx, qy, rx, ry, 180, aPen); drawKochEdge(rx, ry, px ,py, 60, aPen); } // This code recursively draws a Koch edge public void drawKochEdge(int sx, int sy, int ex, int ey, int a, Graphics p) { int length = (int)(Point.distance(sx, sy, ex, ey) / 3.0); if (length < 2) p.drawLine(sx,sy,ex,ey); else { int px = sx + (int)(length * Math.cos(Math.toRadians(a))); int py = sy + (int)(length * Math.sin(Math.toRadians(a + 180))); int qx = px + (int)(length * Math.cos(Math.toRadians(a + 60))); int qy = py + (int)(length * Math.sin(Math.toRadians(a + 60 + 180))); int rx = qx + (int)(length * Math.cos(Math.toRadians(a - 60))); int ry = qy + (int)(length * Math.sin(Math.toRadians(a - 60 + 180))); drawKochEdge(sx, sy, px, py, a, p); drawKochEdge(px, py, qx, qy, a+60, p); drawKochEdge(qx, qy, rx, ry, a-60, p); drawKochEdge(rx, ry, ex, ey, a, p); } } // Create the panel in a window and make it visible public static void main(String args[]) { JFrame frame = new JFrame("Koch Snowflake"); frame.add(new KochPanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // Makes size according to panel's preference frame.setVisible(true); } }