Understand BufferStrategy

后端 未结 1 1253
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 09:34

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

相关标签:
1条回答
  • 2020-12-25 10:10

    Here's how it works:

    1. The 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.
    2. When it comes time to draw your stuff, you are retrieving a 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.
    3. When you finally call 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.

    0 讨论(0)
提交回复
热议问题