I have a question. Recently I was looking into ways to implement hardware rendering using Java. My goal was not to use an external library such as OpenGL. I found a post on a website that detailed how to do so.
This is what the code was (I renamed some items):
@Override
public void paint(Graphics g) {
createVolatileImage();
do {
GraphicsConfiguration gc = getGraphicsConfiguration();
Graphics offscreenGraphics = volatileImage.getGraphics();
int validationCode = volatileImage.validate(gc);
if (validationCode == VolatileImage.IMAGE_INCOMPATIBLE) {
createVolatileImage();
}
offscreenGraphics.setColor(getBackground());
offscreenGraphics.fillRect(0, 0, getSize().width, getSize().height);
offscreenGraphics.setColor(getForeground());
paint(offscreenGraphics);
g.drawImage(volatileImage, 0, 0, this);
} while (volatileImage.contentsLost());
}
private void createVolatileImage() {
GraphicsConfiguration gc = getGraphicsConfiguration();
volatileImage = gc.createCompatibleVolatileImage(getWidth(), getHeight());
}
Unfortunately, if I resize the window – the paint ( Graphics ) method (in the class Canvas) gets called like 1,000 times within a second, causing an OutOfMemoryException.
Has anyone encountered this before?
Thanks a lot in advance!
The reason you are getting an OutOfMemoryException is because you never clean up your
VolatileImage. The way I see it, you are allocating a newVolatileImageevery timepaint()is called, which can happen many hundreds (or in your case over a thousand) times per second. Unless you free the memory used by theVolatileImageor fix things so that you make the allocation once instead of once per frame, your application’s memory space will balloon until you crash the JVM. Try adding a call tooffscreengraphics.dispose()at the end of your rendering loop. Also read the Javadoc.EDIT:
Another useful reference.