import java.awt.*; public class BouncingBall extends AnimationApplet{ protected Color color = Color.green; // radius of the ball protected int radius = 20; protected int x, y; // how much the location changes at every redraw protected int dx = -2, dy = -4; // off screen image protected Image image; // off screen graphics protected Graphics offscreen; // dimensions of the applet region protected Dimension d; public void init() { String att = getParameter("delay"); if (att != null) { setDelay(Integer.parseInt(att)); } else{ setDelay(100); // default } d = getSize(); // set the starting point of the ball x = d.width * 2 / 3; y = d.height - radius; } public void update(Graphics g) { // create the off-screen image buffer // if it is invoked the first time if (image == null) { image = createImage(d.width, d.height); offscreen = image.getGraphics(); } // draw the background offscreen.setColor(Color.white); offscreen.fillRect(0,0,d.width,d.height); // adjust the position of the ball // reverse the direction if it touches // any of the four sides if (x < radius || x > d.width - radius) { dx = -dx; } if (y < radius || y > d.height - radius) { dy = -dy; } x += dx; y += dy; // draw the ball offscreen.setColor(color); offscreen.fillOval(x - radius, y - radius, radius * 2, radius * 2); // copy the off-screen image to the screen g.drawImage(image, 0, 0, this); } public void paint(Graphics g) { update(g); } }