import java.applet.Applet; import java.awt.*; // This appears in Core Web Programming from // Prentice Hall Publishers, and may be freely used // or adapted. 1997 Marty Hall, hall@apl.jhu.edu. /** Draw random circles in a background thread. * Needs an external event to start/stop drawing. */ public class RandomCircles extends Applet implements Runnable { private boolean drawCircles = false; public void init() { setBackground(Color.white); } public void startCircles() { Thread t = new Thread(this); t.start(); } public void run() { drawCircles = true; Color[] colors = { Color.lightGray, Color.gray, Color.darkGray, Color.black }; int colorIndex = 0; Graphics g = getGraphics(); while(drawCircles) { int x = (int)Math.round(size().width * Math.random()); int y = (int)Math.round(size().height * Math.random()); g.setColor(colors[colorIndex]); colorIndex = (colorIndex + 1) % colors.length; g.fillOval(x, y, 10, 10); pause(0.1); } } public void stopCircles() { drawCircles = false; } private void pause(double seconds) { try { Thread.sleep((int)(Math.round(seconds * 1000.0))); } catch(InterruptedException ie) {} } }