/* This example demonstrates a bouncing ball with trails */ import java.awt.*; import java.applet.*; public class Bounce3 extends Applet implements Runnable { private static final int XSIZE = 30; private static final int YSIZE = 30; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2; Thread myThread; Image offscreenImg; Graphics offscreenG; Color [] ballColors = {Color.red, Color.green, Color.pink, Color.yellow, Color.orange, Color.blue, Color.magenta, Color.cyan, Color.white}; int colorIndex = 0; boolean justaRedBall = true; public void init() { offscreenImg = createImage(size().width, size().height); offscreenG = offscreenImg.getGraphics(); } public void start() { if (myThread == null) { myThread = new Thread(this); myThread.start(); } } public void stop() { if (myThread != null) { myThread.stop(); myThread = null; } } public boolean mouseDown(Event e, int x, int y) { justaRedBall = !justaRedBall; return true; } public void run() { int trailCntl = 0; while (true) { repaint(); x += dx; y += dy; Dimension d = size(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d.width) { x = d.width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d.height) { y = d.height - YSIZE; dy = -dy; } trailCntl = (trailCntl + 1) % 8; if (trailCntl == 0) colorIndex = (colorIndex + 1) % 9; try { Thread.sleep(15); } catch(InterruptedException e) {} } } public void paint(Graphics g) { if (justaRedBall) { offscreenG.setColor(Color.black); offscreenG.fillRect(0,0,size().width, size().height); offscreenG.setColor(Color.red); offscreenG.fillOval(x, y, XSIZE, YSIZE); g.drawImage(offscreenImg, 0, 0, this); } else { offscreenG.setColor(ballColors[colorIndex]); offscreenG.fillOval(x, y, XSIZE, YSIZE); g.drawImage(offscreenImg, 0, 0, this); } } public void update(Graphics g) { paint(g); } }