import java.awt.*; /** * OffscreenImageExample -- creating and drawing * to an offscreen image and graphics object. * *

* The image is created once off screen and then rendered repeatedly * onto random locations in the applet. */ public class OffscreenImageExample extends java.applet.Applet implements Runnable{ Image offscreenImage; Thread paintThread; /** * Creates and draws to an offscreen image (a series of * green squares on top of a black background. */ public void init() { Dimension dim = size(); int offscreenSize = Math.min(dim.width / 2, dim.height / 2); offscreenImage = createImage(offscreenSize, offscreenSize); Graphics offscreenGraphics = offscreenImage.getGraphics(); offscreenGraphics.setColor(Color.black); offscreenGraphics.fillRect(0, 0, offscreenSize, offscreenSize); offscreenGraphics.setColor(Color.green); for (int i = 1; i < offscreenSize; i += 6) { int x = (offscreenSize - i) / 3; int y = (offscreenSize - i) / 3; offscreenGraphics.drawRect(x, y, i, i); } } /** Starts the animation thread when the applet starts. */ public void start() { paintThread = new Thread(this); paintThread.start(); } /** Stops the animation thread when the applet stops. */ public void stop() { paintThread.stop(); paintThread = null; } /** * Runs the repaint() loop with some sleeping time between * updates. */ public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Interrupted during sleep."); } repaint(); } } /** * Renders the offscreen image onto the applet at random * points in the upper left corner of the applet. */ public void paint(Graphics g) { Dimension dim = size(); g.setColor(Color.blue); g.drawRect(0, 0, dim.width - 1, dim.height - 1); int x = (int) (Math.random() * dim.width / 2); int y = (int) (Math.random() * dim.height / 2); g.drawImage(offscreenImage, x, y, this); } }