// Applet to simulate a Brownian path in a rectangle // It's a polygonal path with random displacements import java.awt.Graphics; import java.awt.Polygon; import java.awt.Color; import java.awt.Component; import java.lang.Math; import java.util.Random; public class BrownianApplet extends java.applet.Applet implements Runnable { int delta = 2; // length of each step int cur_x = 100, cur_y = 100; // starting point Polygon path; Thread myThread; Random rng; int pause = 100; // time between steps in milliseconds // The init method is called when the applet starts public void init(){ path = new Polygon(); // create an empty path rng = new Random(); setBackground(Color.red); } // The start method is called everytime the applet is (re)started // All this one does is begin a thread of execution public void start(){ if(myThread == null){ myThread = new Thread(this); myThread.start(); } } public void stop(){ if(myThread != null){ myThread.stop(); myThread = null; // allow garbage collection } } public void run(){ // Create Path while(true){ int pmx,pmy; pmx = ( rng.nextDouble() < 0.5 ? 1 : -1); pmy = ( rng.nextDouble() < 0.5 ? 1 : -1); path.addPoint(cur_x ,cur_y ); cur_x += pmx*delta; cur_y += pmy*delta; repaint(); try { Thread.sleep(1000);} catch (InterruptedException e) {} } } public void paint(Graphics g){ g.drawPolygon(path); // draw path } }