import java.awt.*; import java.lang.*; import java.util.*; import java.awt.event.*; /** * Great Ideas in Computer Science: Chapter 6: Fractal * * @author Ben Allen (bta@duke.edu) * * This applet is the implementation of the fractal program discussed in Chapter 6. * The program was originally coded in pascal by D. J. Miller. Some of the original * code has been translated and used in this applet. Comments have been included in these * parts to give Miller credit. * */ public class fractal extends java.applet.Applet implements ActionListener { double x,y,x0,y0,x1,y1,z,m,n,c1,c2; int i,j; int canvasXmax=200; //Screen coordinates defined on following lines int canvasYmax=200; double xmax=200; double ymax=200; double xmin=0; double ymin=0; Canvas graphArea; Button enterB; TextField c1Field,c2Field; /** * Applet initialized */ public void init() { graphArea = new Canvas(); graphArea.setSize(canvasXmax,canvasYmax); enterB = new Button("Enter"); enterB.addActionListener(this); c1Field = new TextField(10); c2Field = new TextField(10); add(new Label("Constant1")); add(c1Field); add(new Label("Constant2")); add(c2Field); add(enterB); add(graphArea); } /** * Button handler method */ public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause==enterB) { String tempString=""; //Temp variables used to input doubles from TextFields Double tempDouble; tempString = c1Field.getText(); //Method of receiving doubles from TextFields tempDouble=new Double(tempString); c1 = tempDouble.doubleValue(); tempString = c2Field.getText(); tempDouble=new Double(tempString); c2 = tempDouble.doubleValue(); drawFractal(); } } /** * This procedure draws the fractal. Originally coded in Turbo Pascal by Miller. Slight * modifications have been made. */ public void drawFractal() { Graphics g = graphArea.getGraphics(); g.clearRect(0,0,canvasXmax,canvasYmax); g.setColor(Color.black); m=0; while (m<=200) { x0=-2+(m/50); n=0; while (n<=100) //For each y on initial half { y0=2-(n/50); x=x0; y=y0; i=1; z=0; while ((i<=20) && (z<=4)) //check convergence { x1=(x*x) - (y*y) +c1; y1=(2*x*y) +c2; x=x1; y=y1; z=(x*x)+(y*y); i=i+1; } if (z<=4) //If convergence, plot { g.drawLine(screenX(m),screenY(n),screenX(m),screenY(n)); //plot first half g.drawLine(screenX(200-m),screenY(200-n),screenX(200-m),screenY(200-n)); //plot second half } n=n+1; } m=m+1; } } /** * Return x to be plotted to screen */ int screenX(double realX) { return (int)realX; } /** * Return y to be plotted to screen */ int screenY(double realY) { return (int)(canvasYmax-realY); } }