/* Program 19.9: Bounce2 This example has been improved over what was in the book. It uses t.suspend() and t.resume() instead of t.start() and t.stop(). It has also added start() and stop() methods to the applet (which are different from the thread's start and stop methods). The applet's start and stop methods suspend() and resume() the thread when the user has moved off the page so CPU cycles aren't wasted drawing pictures the user never sees. */ import java.awt.Graphics; import java.applet.Applet; import java.awt.Rectangle; import java.awt.Color; import java.awt.Event; import java.awt.Dimension; import java.awt.Image; public class Bounce2 extends Applet implements Runnable { Rectangle r; int x_increment = 1; int y_increment = 1; Thread t; boolean bouncing; public final synchronized void update (Graphics g) { Image offScreenImage = createImage(size().width, size().height); paint(offScreenImage.getGraphics()); g.drawImage(offScreenImage, 0, 0, null); } public void init () { r = new Rectangle( 30, 40, 20, 20); t = new Thread(this); t.start(); bouncing = true; } public void start() { if (!bouncing) { t.resume(); bouncing = true; } } public void stop() { if (bouncing) { t.suspend(); bouncing = false; } } public void paint (Graphics g) { g.setColor(Color.red); g.fillOval(r.x, r.y, r.width, r.height); } public boolean mouseUp(Event e, int x, int y) { if (bouncing) { t.suspend(); bouncing = false; } else { t.resume(); bouncing = true; } return true; } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (true) { // infinite loop r.x += x_increment; r.y += y_increment; if (r.x >= size().width || r.x < 0) x_increment *= -1; if (r.y >= size().height || r.y < 0) y_increment *= -1; repaint(); try { Thread.currentThread().sleep(100); } catch (Exception e) { } } } }