import java.awt.*; import java.awt.event.*; public class c04_staircase extends java.applet.Applet { double r = (double)1/3; int n = 7; boolean devil = true; static final int left = 30; static final int w = 300; Graph graph; Controls controls; class Graph extends Canvas { public void paint(Graphics g) { cantor(g, 1, left, left+(1+(devil?1:0))*w/2, left+w, left+(1-(devil?1:0))*w/2); double d = r < 1 ? Math.log(2)/Math.log(2/(1-r)) : 0; g.drawString("Dimension of Cantor set: "+d, 10, 20); } private void cantor(Graphics g, int level, double x1, double y1, double x2, double y2) { if (level < n) { double x = ((1+r)*x1+(1-r)*x2)/2; double y = (y1+y2)/2; cantor(g, level+1, x1, y1, x, y); double xx = ((1-r)*x1+(1+r)*x2)/2; if (devil) { g.drawLine((int)x, (int)y, (int)xx, (int)y); } cantor(g, level+1, xx, y, x2, y2); } else { g.drawLine((int)x1, (int)y1, (int)x2, (int)y2); } } } class Controls extends Container { private TextField tr; private TextField tn; private Checkbox td; 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(td = new Checkbox("Staircase", devil)); 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()); devil = td.getState(); } catch (NumberFormatException nfx) { } c04_staircase.this.graph.repaint(); } } ); } } public void init() { setLayout(new BorderLayout()); add(controls = new Controls(), BorderLayout.SOUTH); add(graph = new Graph(), BorderLayout.CENTER); } }