import java.awt.*; import javax.swing.JPanel; public class KochPanel extends JPanel { private final int PANEL_WIDTH = 400; private final int PANEL_HEIGHT = 400; private final double SQ = Math.sqrt(3.0) / 6; private final int TOPX = 200; private final int TOPY = 20; private final int LEFTX = 60; private final int LEFTY = 300; private final int RIGHTX = 340; private final int RIGHTY = 300; private int current; public KochPanel(int currentOrder) { current = currentOrder; setBackground(Color.black); setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); } // recursively draw the fractal public void drawFractal(int order, int x1, int y1, int x5, int y5, Graphics panel) { int deltaX, deltaY, x2, y2, x3, y3, x4, y4; if (order == 1) { panel.drawLine(x1, y1, x5, y5); } else { deltaX = x5 - x1; // distance between end points deltaY = y5 - y1; // distance between end points x2 = x1 + deltaX / 3; // distance to first third y2 = y1 + deltaY / 3; // distance to first third x3 = (int)((x1 + x5) / 2 + SQ * (y1 - y5)); // tip of point y3 = (int)((y1 + y5) / 2 + SQ * (x5 - x1)); // tip of point x4 = x1 + deltaX * 2/3; // point for second third y4 = y1 + deltaY * 2/3; // point for second third drawFractal(order-1, x1,y1, x2,y2, panel); drawFractal(order-1, x2,y2, x3,y3, panel); drawFractal(order-1, x3,y3, x4,y4, panel); drawFractal(order-1, x4,y4, x5,y5, panel); } } public void paintComponent(Graphics panel) { super.paintComponent(panel); panel.setColor(Color.green); drawFractal(current, TOPX, TOPY, LEFTX, LEFTY, panel); drawFractal(current, LEFTX, LEFTY,RIGHTX, RIGHTY, panel); drawFractal(current, RIGHTX, RIGHTY,TOPX, TOPY, panel); } public void setOrder(int o) { current = o; } public int getOrder() { return current; } }