//BounceBall.java //Illustrates the animation loop with an image //Andy Harris, 06/00 import java.awt.*; import java.applet.*; public class BounceBall extends Applet implements Runnable { int dx = 10; int dy = 10; int ballX = 0; int ballY = 0; Image imgBall; AudioClip sndBoing; Thread looper; boolean keepGoing = false; public void init(){ imgBall = getImage(getCodeBase(), "ball.gif"); sndBoing = getAudioClip(getCodeBase(), "boing.au"); } // end if public void start(){ if (looper == null){ looper = new Thread(this); keepGoing = true; looper.start(); } // end if } // end start public void stop(){ keepGoing = false; looper = null; } // end stop public void run(){ while (keepGoing){ int appWidth = getSize().width; int appHeight = getSize().height; try { looper.sleep(100); } catch (InterruptedException exc){ System.out.println(exc.getMessage()); } // end try ballX += dx; ballY += dy; if (ballX > appWidth - imgBall.getWidth(this)){ dx = -dx; sndBoing.play(); } // end if if (ballX < 0){ dx = -dx; sndBoing.play(); } // end if if (ballY > appHeight - imgBall.getHeight(this)){ dy = -dy; sndBoing.play(); } // end if if (ballY < 0){ dy = - dy; sndBoing.play(); } // end if repaint(); } // end while } // end run public void paint(Graphics g){ g.drawImage(imgBall, ballX, ballY, this); } // end paint } // end class def