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 called double 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 blank Image object. Now you will see
how to draw on that image rather than the screen. As you recall from earlier chapters, you
need a Graphics object in order to use any of Java's rendering methods. Conveniently, the
Graphics object that you can use to draw on an Image is available via the getGraphics( )
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, call drawImage( ). 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();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home