views:

49

answers:

2

How can I draw a portion of my Java2D simulation that doesn't change to an image/buffer so I don't have to redraw it's primitives each time?

I have a portion of my Java2D simulation that requires me to draw thousands of small lines. However, this portion of the app doesn't change once drawn so it doesn't make sense to re-draw thousands of primitives each loop iteration (doing active rendering).

So, what object do I use to draw to and preserve it, and then allow me to simply draw this whole image to my canvas, and then draw on top of it what changes?

+2  A: 

One could draw out to a BufferedImage, then later, draw the contents of the BufferedImage to a Swing component, like a JPanel.

In order to draw to a BufferedImage, one would use the createGraphics to obtain the Graphics2D context of the image:

BufferedImage img = new BufferedImage(width, height, type);
Graphics2D g = img.createGraphics();
// do drawing using the Graphics2D object.
g.dispose();

Then later, draw the contents of the BufferedImage to a JPanel by overriding the paintComponent method:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, null);  // Draw img onto the JPanel.
}
coobird
A: 

Note that you should also override getPreferredSize() to return the size of your image, or set a preferred size on the JPanel equal to the size of your image. If you don't do this, you'll have layout problems with your JPanel subclass.

uckelman