import java.awt.*; public class BouncingBall extends AnimationApplet{ protected Color color = Color.magenta; // radius of the ball protected int radius = 20; protected int radius2 = 20; protected int x1, y1; protected int x2, y2; protected int dist; // how much the location changes at every redraw protected int dx1 = -2, dy1 = -4; protected int dx2 = -2, dy2 = -4; // off screen image protected Image image1; protected Image image2; // 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 x1 = d.width * 2 / 3; y1 = d.height - radius; x2 = d.width * 2 / 4; y2 = d.height - radius; } public void update(Graphics g) { // create the off-screen image buffer // if it is invoked the first time if (image1 == null) { image1 = createImage(d.width, d.height); offscreen = image1.getGraphics(); } // draw the background offscreen.setColor(Color.cyan); 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 (x1 < radius || x1 > d.width - radius) { dx1 = -dx1; } if (y1 < radius || y1 > d.height - radius) { dy1 = -dy1; } x1 += dx1; y1 += dy1; if (x2 < radius || x2 > d.width - radius) { dx2 = -dx2; } if (y2 < radius || y2 > d.height - radius) { dy2 = -dy2; } x2 += dx2; y2 += dy2; double XResult = x2 - x1; double YResult = y2 - y1; double Dist = Math.pow(XResult, 2) + Math.pow(YResult, 2); double DResult = Math.sqrt(Dist); if ((DResult < (2 * radius)) || (DResult == (2 * radius ))) { DResult = DResult + 40; dx2 = -dx2 + 1; // Reverse the direction if it collides dy2 = -dy2; dx1 = -dx1 + 1; dy1 = -dy1 + 1; } // draw the ball offscreen.setColor(color); offscreen.fillOval(x1 - radius, y1 - radius, radius * 2, radius * 2); offscreen.fillOval(x2 - radius, y2 - radius, radius * 2, radius * 2); // copy the off-screen image to the screen g.drawImage(image1, 0, 0, this); } public void paint(Graphics g) { update(g); } }