Archive

Simple Double Buffering in Java

I recently wrote a simple program that had a background image, with smaller, draggable images over top of it. It worked fine when both the images and background were in the same JPanel, but when I tried to paint them in a JApplet, the dragged objects started to flicker with each call to repaint().

What I found that I needed to do was have all of the objects painted offscreen, added to a temporary image, and then that image painted into the JApplet (double buffering). That is where using an auxiliary Graphics component comes in.

import java.awt.*;
import javax.swing.*;

public class SomeApplet extends JApplet {
  // ...
  private Graphics bufferGraphics; // graphics buffer
  private Image bufferImage; // temporary offscreen image

public void init() {
    // ...
    bufferImage = createImage(*WIDTH*, *HEIGHT*);
    bufferGraphics = bufferImage.getGraphics();
  }

public void paint(Graphics g) {
    bufferGraphics.drawImage(*IMAGE 1*, x, y, null);
    bufferGraphics.drawImage(*IMAGE 2*, x, y, null);
    // ...
    g.drawImage(bufferImage,0,0,null);
  }
}

The key is to paint all of your images using the extra Graphics component, and then paint the temporary image associated with that component using the paint() method’s Graphics component. This way, the whole image is drawn to the canvas only once for each repaint() called.

I’m no Java guru, but I had to do a bit of searching around before figuring out a simple way to do this. A lot of tutorials included extra code which made understanding it difficult. If you find this helpful, let me know by leaving a comment.

MacBook Air + Parody Ad

So I just watched the MacBook Air introduction by Steve Jobs at MacWorld’08, and was pretty impressed. I read an article about the machine so wasn’t surprised when I seen it, but there was some stuff I didn’t know about.

It seemed a let down that there was no CD/DVD drive, but I realized that I barely use the DVD drive in my laptop. Also, the fact that it can wirelessly “borrow” the hard drive of a nearby PC or Mac is pretty awesome, and makes not having that drive more than tolerable. 5 hour battery life, and a full-size, back lit keyboard are certainly a plus.

I think I was even more surprised when I seen that they start at $1800. I certainly couldn’t justify spending that much as a student, but I think it’s a reasonable price.

I couldn’t help but watch a few parody ads while I was at it. This one was particularly good. I think the BSoD did it for me.