How do you write every paintComponent call simultaneously to BufferedImage?

admin

Administrator
Staff member
How do you write every every repaint call (direct or not) by a
Code:
JPanel
-type (i.e. a custom class which
Code:
extends
/inherits from
Code:
JPanel
) to a
Code:
BufferedImage
?

Doing this sort of thing inside the custom class'
Code:
paintComponent
does not work:

Code:
protected void paintComponent(Graphics g) {
    super.paintComponent(g); 
    Graphics2D G2 = (Graphics2D) g;

    // ... draw objects

    BufferedImage imageBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
    G2 = imageBuffer.createGraphics();

    // Which doesn't work, because with that method it seems you would
    // need to call paint() on Graphics2D reference here. 
    // And to do so would then throw an Illegal Exception.
}

The resulting
Code:
BufferedImage
is the correct size of the
Code:
JPanel
-type class which calls
Code:
paintComponent
, but the image is black (i.e. empty) - which is entirely logical because
Code:
createGraphics()
alone does nothing.

I know of Rob Camick's <a href="http://tips4java.wordpress.com/2008/10/13/screen-image/" rel="nofollow">ScreenImage</a> code - but that seems intended for a single screenshot at initialisation of the program.

What leaves me confused is that what
Code:
paintComponent
does must be held in memory before being displayed on-screen... So is there a way of grabbing that every time and saving it into a
Code:
BufferedImage
?