Reputation: 2913
I am making a game and I am trying to find the best way to implement Doublebuffering into it. Would anyone be able to show me how I could do it with my rendering code below?
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(p.getImage(), p.getX(),p.getY(),null);
//draw each ball object
for(int i=0;i<balls.size(); i++){
Ball tmp = (Ball) balls.get(i);
g2d.drawImage(tmp.getImage(), tmp.getX(),tmp.getY(),null);
}
//strings
g2d.drawString("Score: "+score,50,20);
}
Could someone please help?
Upvotes: 1
Views: 105
Reputation: 88757
If you're using Swing you just can use the built-in double buffering: http://java.sun.com/products/jfc/tsc/articles/painting/#db
In case you're implementing your own rendering, here are some hints:
Double Buffering basically means you have two draw buffers that you alternatingly write to while the other is displayed.
In your case, you might use an image to draw your game content to and then draw that image to the component. This should give you double buffering in a sense. You might use two images which you swap in order to reduce concurrent access, i.e. one would be the "front" buffer that is displayed and the other is the "back" buffer you draw to.
That said, I'd strongly recommend not to implement that yourself. Instead you should try and use one of the existing 2D libraries (like Swing) or 3D libraries (like OpenGL with JOGL or LWJGL as Java bindings - note that it doesn't have to be 3D with OpenGL). Alternatively you could also look for a game engine, there are plenty of them out there.
Upvotes: 2