I\'m kind of new to java. I want to make a game. After a lot of research, I can\'t understand how bufferstrategy works.. I know the basics.. it creates an off-screen image t
Here's how it works:
JFrame
constructs a BufferStrategy
when you call createBufferStrategy(2);
. The BufferStrategy
knows that it belongs to that specific instance of JFrame
. You are retrieving it and storing it in the bs
field.Graphics2D
from bs
. This Graphics2D
object is tied to one of the internal buffers owned by bs
. As you draw, everything goes into that buffer.bs.show()
, bs
will cause the buffer that you just drew to become the current buffer for the JFrame
. It knows how to do this because (see point 1) it knows what JFrame
it is in service to.That's all that's going on.
By way of comment to your code...you should change your drawing routine a bit. Instead of this:
try{
g2 = (Graphics2D) bs.getDrawGraphics();
drawWhatEver(g2);
} finally {
g2.dispose();
}
bs.show();
you should have a loop like this:
do {
try{
g2 = (Graphics2D) bs.getDrawGraphics();
drawWhatEver(g2);
} finally {
g2.dispose();
}
bs.show();
} while (bs.contentsLost());
That will safeguard against lost buffer frames, which, according to the docs, can happen occasionally.