import java.awt.*; import java.awt.event.*; public class c03_koch extends java.applet.Applet { double r = 0.29; int n = 5; Graph graph; Controls controls; class Graph extends Canvas { public void paint(Graphics g) { koch(g, 1, 30, 190, 30+300, 190); } private void koch(Graphics g, int level, double x1, double y1, double x2, double y2) { if (level < n) { double nx = (2*x1+x2)/3; double ny = (2*y1+y2)/3; koch(g, level+1, x1, y1, nx, ny); double ox = nx; double oy = ny; nx = (x1+x2)/2 - r*(y1-y2); ny = (y1+y2)/2 + r*(x1-x2); koch(g, level+1, ox, oy, nx, ny); ox = nx; oy = ny; nx = (x1+2*x2)/3; ny = (y1+2*y2)/3; koch(g, level+1, ox, oy, nx, ny); koch(g, level+1, nx, ny, x2, y2); } else { g.drawLine((int)x1, (int)y1, (int)x2, (int)y2); } } } class Controls extends Container { private TextField tr; private TextField tn; private Button redraw; public Controls() { setLayout(new FlowLayout()); add(new Label("r =", Label.RIGHT)); add(tr = new TextField(""+r, 6)); add(new Label("n =", Label.RIGHT)); add(tn = new TextField(""+n, 6)); add(redraw = new Button("Redraw")); redraw.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { r = Double.valueOf(tr.getText()).doubleValue(); n = Integer.parseInt(tn.getText()); } catch (NumberFormatException nfx) { } c03_koch.this.graph.repaint(); } } ); } } public void init() { setLayout(new BorderLayout()); add(controls = new Controls(), BorderLayout.SOUTH); add(graph = new Graph(), BorderLayout.CENTER); } }