9.5. Double Buffering
One important application of offscreen images is double buffering. This is a technique that eliminates flicker in animated graphics. Double buffering gets its name from the fact that there are two graphics areas (buffers) involved—the onscreen buffer and the offscreen image. Animation is just the process of showing one frame after another. Without double buffering, you simply clear the drawing area and draw the new frame. Repeated clearing and redrawing produces flicker, as shown in the next example, Annoyance. This class simply renders a filled rectangle at the coordinates of the last mouse motion event. When you move the mouse around in the window, you'll notice the flicker.
import java.awt.*;
import java.awt.event.*;
public class Annoyance
extends ApplicationFrame
implements MouseMotionListener {
public static void main(String[] args) {
new Annoyance();
}
private int mX, mY;
public Annoyance() {
super("Annoyance v1.0");
addMouseMotionListener(this);
setVisible(true);
}
public void mouseMoved(MouseEvent me) {
mX = (int)me.getPoint().getX();
mY = (int)me.getPoint().getY();
repaint();
}
public void mouseDragged(MouseEvent me) { mouseMoved(me); }
public void paint(Graphics g) {
int s = 100;
g.setColor(Color.blue);
g.fillRect(mX - s / 2, mY - s / 2, s, s);
}
}
Double buffering eliminates the flicker from this example. Basically, I'll render the rectangle into an offscreen image and then transfer the image to the screen. This erases the old picture and draws ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access