Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
This flashing is distracting and causes the user to perceive your rendering as slower than it
actually is. Use of an offscreen image to reduce flicker is calleddouble buffering,because the
screen is considered a buffer for pixels, and the offscreen image is the second buffer, where
you can prepare pixels for display.
Earlier in this chapter, you saw how to create a blankImageobject. Now you will see
how to draw on that image rather than the screen. As you recall from earlier chapters, you
need aGraphicsobject in order to use any of Java’s rendering methods. Conveniently, the
Graphicsobject that you can use to draw on anImageis available via thegetGraphics( )
method. Here is a code fragment that creates a new image, obtains its graphics context,
and fills the entire image with red pixels:

Canvas c = new Canvas();
Image test = c.createImage(200, 100);
Graphics gc = test.getGraphics();
gc.setColor(Color.red);
gc.fillRect(0, 0, 200, 100);

Once you have constructed and filled an offscreen image, it will still not be visible.
To actually display the image, calldrawImage( ). Here is an example that draws a time-
consuming image, to demonstrate the difference that double buffering can make in perceived
drawing time:

/*
* <applet code=DoubleBuffer width=250 height=250>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class DoubleBuffer extends Applet {
int gap = 3;
int mx, my;
boolean flicker = true;
Image buffer = null;
int w, h;

public void init() {
Dimension d = getSize();
w = d.width;
h = d.height;
buffer = createImage(w, h);
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
mx = me.getX();
my = me.getY();
flicker = false;
repaint();
}
public void mouseMoved(MouseEvent me) {
mx = me.getX();
my = me.getY();

760 Part II: The Java Library

Free download pdf