//RandomWalkAnimation.java import java.awt.*; import java.awt.event.*; //**ActionListener "interface" import javax.swing.*; public class RandomWalkAnimation extends JApplet implements ActionListener { //*** int animationDelay; //** millisecond delay Timer animationTimer; //** Timer drives animation. //initialize Timer object with a time in ms, it will automatically //fire event periodically. double totalDist; //*moved from paint int xPrev, yPrev, xNow, yNow; //*moved from paint int steps; public void init() { String input; input = JOptionPane.showInputDialog("Enter animation delay in ms"); animationDelay = Integer.parseInt(input); //initialize (**moved from paint) xPrev = xNow = getWidth()/2; //start in center yPrev = yNow = getHeight()/2; steps = 0; totalDist = 0; startAnimation(); //*** begin animation } //** will be called once every animationDelay ms. //**Notice there is no loop in paint. public void paint( Graphics g ) { double avgDist=0, dist; int scale=5; //conversion to screen pixels steps++; switch ((int)(Math.random()*4)) { case 0: //up yNow = yPrev - scale; break; case 1: //down yNow = yPrev + scale; break; case 2: //left xNow = xPrev - scale; break; case 3: //left xNow = xPrev + scale; break; } g.drawLine(xPrev,yPrev,xNow,yNow); xPrev = xNow; yPrev = yNow; int x = (xNow - getWidth()/2) / scale; int y = (yNow - getHeight()/2) / scale; dist = Math.sqrt(x*x+y*y); totalDist += dist; avgDist = totalDist / steps; showStatus("Distance from origin: " + (int)dist + " Average distance: " + (int)avgDist); } //** Generic animation stuff: use this as is for any animation. // respond to Timer's event. //Must have this method if implementing ActionListener public void actionPerformed( ActionEvent actionEvent ) { repaint(); // repaint animator. ** calls paint method } // start or restart animation public void startAnimation() { if ( animationTimer == null ) { animationTimer = new Timer( animationDelay, this ); animationTimer.start(); } else // continue from last image displayed if ( ! animationTimer.isRunning() ) animationTimer.restart(); } // stop animation timer public void stopAnimation() { animationTimer.stop(); } }