Understand BufferStrategy

I'm kind of new to java. I want to make a game. After many studies, I cannot understand how the buffer strategy works. I know the basics .. it creates an off-screen image that you can later paste into your Windows object. I got it

public class Marco extends JFrame { private static final long serialVersionUID = 1L; BufferStrategy bs; //create an strategy for multi-buffering. public Marco() { basicFunctions(); //just the clasics setSize,setVisible,etc createBufferStrategy(2);//jframe extends windows so i can call this method bs = this.getBufferStrategy();//returns the buffer strategy used by this component } @Override public void paint(Graphics g){ g.drawString("My game",20,40);//some string that I don't know why it does not show //guess is 'couse g2 overwrittes all the frame.. Graphics2D g2=null;//create a child object of Graphics try{ g2 = (Graphics2D) bs.getDrawGraphics();//this new object g2,will get the //buffer of this jframe? drawWhatEver(g2);//whatever I draw in this method will show in jframe, //but why?? }finally{ g2.dispose();//clean memory,but how? it cleans the buffer after //being copied to the jframe?? when did I copy to the jframe?? } bs.show();//I never put anything on bs, so, why do I need to show its content?? //I think it a reference to g2, but when did I do this reference?? } private void drawWhatEver(Graphics2D g2){ g2.fillRect(20, 50, 20, 20);//now.. this I can show.. } } 

I don’t know .. I studied this for a long time .. and no luck at all. I don’t know .. Maybe it’s all there, and it’s really clear and simple, and I’m just too stupid to see it.

Thanks for all the help .. :)

+7
source share
1 answer

Here's how it works:

  • JFrame builds a BufferStrategy when you call createBufferStrategy(2); . BufferStrategy knows that it belongs to this particular JFrame instance. You extract it and save it in the bs field.
  • When the time comes to draw your stuff, you are extracting Graphics2D from bs . This Graphics2D object is bound to one of the internal buffers owned by bs . When you draw, everything goes to this buffer.
  • When you finally call bs.show() , bs will cause the buffer you just drawn to become the current buffer for the JFrame . He knows how to do this because (see Clause 1) he knows that he is in maintenance of the JFrame .

That is all that happens.

As a comment on your code ... you need to slightly modify your drawing procedure. 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()); 

This will protect against lost buffer frames, which, according to docs , can occur occasionally.

+18
source

All Articles