Hello I’m writing a small game and it’s nearly finished, the only thing that doesn’t work is the ImageBuffer. Every 10 miliseconds I call the method repaint(). My paint() method is as follows:
private Graphics2D g2D;
public void paint (Graphics g) {
BufferedImage bimage = ((Graphics2D)g).getDeviceConfiguration().createCompatibleImage(700, 600, Transparency.OPAQUE);
g2D = bimage.createGraphics();
g2D.setFont(font);
for(Wall wall: walls){
wall.paint(g2D);
}
g2D.setColor(Color.orange);
paddle.paint(g2D);
g2D.drawString(score + "", 150,50);
g2D.drawString("record: "+topscore , 350,50);
g2D.setColor(Color.red);
ball.paint(g2D);
g.drawImage(bimage,0,0,this);
}
But this doesn’t seem to remove the flickering. I think somehow the screen is cleared before the bufferedimage starts being painted.
Can anyone help me with solving this problem?
thanks!
You should extend
JComponentinstead ofCanvas, depending on if you are using Swing rather than AWT. Doing this gives you a nice lightweight component and doesn’t need you to implement double-buffering support. Then, in your overriddenpaintComponent(..)draw your image with the provided Graphics object.On the subject of the original code, creating a new compatible image every single time in paint is blooming horrible (it’s a very expensive operation that uses large bytebuffers — you’ll get frequent GC pauses). If you really want double buffering in AWT (which will give you flickering when resizing but should be okay in an applet), you should look into BufferStrategy.
Edit: changed Component to JComponent, oops 🙂