Return to article
Double Buffering: Example6Applet
Here is the drawing code for the applet that
is shown above. The code for the entire applet can be found in
Example6Applet.java.
Dimension offDimension;
Image offImage;
Graphics offGraphics;
/**
* Update a frame of animation.
*/
public void update(Graphics g) {
Dimension d = size();
// Create the offscreen graphics context
if ((offGraphics == null)
|| (d.width != offDimension.width)
|| (d.height != offDimension.height)) {
offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}
// Erase the previous image
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
offGraphics.setColor(Color.black);
// Paint the frame into the image
paintFrame(offGraphics);
// Paint the image onto the screen
g.drawImage(offImage, 0, 0, null);
}
/**
* Paint the previous frame (if any).
*/
public void paint(Graphics g) {
if (offImage != null) {
g.drawImage(offImage, 0, 0, null);
}
}
/**
* Paint a frame of animation.
*/
public void paintFrame(Graphics g) {
Dimension d = size();
int h = d.height / 2;
for (int x = 0 ; x < d.width ; x++) {
int y1 = (int)((1.0 + Math.sin((x - frame) * 0.05)) * h);
int y2 = (int)((1.0 + Math.sin((x + frame) * 0.07)) * h);
g.drawLine(x, y1, x, y2);
}
}