Below, is a "complete" program. It draws 10 randomly placed lines of randomly selected colors on the image at a time; in a separate thread, it then displays the "updated" image. The drawing is done in the paint method, and the display is done in the run method. Other applications that used this architecture would move an object across the screen in the paint method one increment at a time, display one of a list of images for an animation, etc.
import java.applet.*;
import java.awt.*;
import java.util.*;
public class DoubleBuf extends Applet implements Runnable {
boolean pause = false;
Thread runThread = null;
Image offScreen;
int rd, gr, bl;
int x1, y1, x2, y2;
Color c;
Color backGround = new Color (0xffffff);
int imageWidth, imageHeight;
Random random;
// ************* init
public void init () {
random = new Random ();
} // end init
// ************* start
public void start () {
runThread = new Thread ( this );
runThread.start ();
} // end start
// ************* stop
public void stop () {
if ( runThread != null ) runThread.stop ();
runThread = null;
} // end stop
// ************* mouseDown
public boolean mouseDown ( Event event, int x, int y) {
if ( runThread != null ) pause = true;
else {
pause = false;
start ();
} // end else;
return true;
} // end stop
// ************* paint
public void paint ( Graphics g, Dimension d ) {
for ( int i = 0; i < 10; i++ ) {
rd = (int)( 255 * random.nextFloat () );
gr = (int)( 255 * random.nextFloat () );
bl = (int)( 255 * random.nextFloat () );
x1 = (int)( d.width * random.nextFloat () );
y1 = (int)( d.height * random.nextFloat () );
x2 = (int)( d.width * random.nextFloat () );
y2 = (int)( d.height * random.nextFloat () );
g.setColor ( new Color ( rd, gr, bl ) );
g.drawLine ( x1, y1, x2, y2 );
} // end for
} // end paint
// ************* run thread
public void run () {
Dimension d;
Graphics g;
while ( ! pause ) {
d = this.size ();
if ( ( offScreen == null ) ||
( imageWidth != d.width ) ||
( imageHeight != d.height ) ) {
offScreen = this.createImage ( d.width, d.height );
imageWidth = d.width;
imageHeight = d.height;
} // end if
g = offScreen.getGraphics ();
paint ( g, d );
g = this.getGraphics ();
g.drawImage ( offScreen, 0, 0, Color.white, this );
try {Thread.sleep ( 10 );} catch ( InterruptedException e) {;}
} // end while
runThread = null;
} // end run
} // end DoubleBuf