//Animation Applet //M.Dubson, Feb. 1999, ENVD 3252 import java.awt.*; import java.applet.Applet; import java.awt.event.*; import java.lang.Thread; public class Animation extends Applet implements Runnable { Thread theThread; Image offscreen; int w,h; //width and height of screen int a; //acceleration of gravity int nbrBalls; //Number of balls int x[], y[]; // x-, y-coordinates of ball position int vx[], vy[]; // x-, y-coordinates of ball velocity int r1; //radius of ball public void init() { nbrBalls = 8; a = 1; w = getSize().width; h = getSize().height; x = new int[nbrBalls]; y = new int[nbrBalls]; vx = new int[nbrBalls]; vy = new int[nbrBalls]; for(int i = 0; i < nbrBalls; i++) { x[i] = w/2 + (int)(Math.random()*w/5 - w/10); y[i] = h/2 + (int)(Math.random()*h/5 - h/10); vx[i] = (int)(Math.random()*11 - 20); vy[i] = (int)(Math.random()*8); r1 = w/30; } } public void update( Graphics g ) { if (offscreen == null || offscreen.getHeight(this) != h || offscreen.getWidth(this) != w) { offscreen = createImage(w, h);} Graphics g2 = offscreen.getGraphics(); paint(g2); g.drawImage( offscreen, 0, 0, this); } public void step() { Graphics g = getGraphics(); for (int i=0; i (w-2*r1)) { vx[i] *= -1; } if( (vy[i] <0 && y[i] <= 2*r1) || (vy[i]>0 && y[i] >= h - 2*r1) ) { vy[i] *= -1; } vy[i] += a; x[i] += vx[i]; y[i] += vy[i] ; } repaint(); }//End of step method public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0,0,w,h); for (int i = 0; i < nbrBalls; i++) { int red = i*128/nbrBalls +127; g.setColor(new Color(red, 0, 0)); g.fillOval( x[i]-r1, y[i] - r1, 2*r1, 2*r1); } }//end of paint method public void start() { if( theThread == null ){theThread = new Thread( this );} theThread.start(); } public void run() { while( true ) { step(); try { theThread.sleep( 40 ); } catch( Exception e ) {;} } }//end of run method public void stop() { if( theThread != null && theThread.isAlive() ) { theThread.stop(); } theThread = null; } } // End of class Animation