javagraphicsbuffergraphics2dbufferstrategy

what happens to the value returned by 'createBufferStrategy'?


I'm learning about BufferStrategy and I'm kind of confused with the creation of BS.

my code looks like this...

public class Game extends Canvas{


    /*code not relevant to this topic..
                                       */



    public void render(){
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null){
             createBufferStrategy(3);
        }
    }

}

basically, my class 'Game' is a subclass of Canvas.. and that class get's the buffer strategy and stores it in bs.

However, bs did not "create" a buffer strategy and if it is null (which in this case it is), i say "createBufferStrategy(3)".

I'm confused as to what happens when I createBufferStrategy(3) or this.createBufferStrategy(3) (which is the same thing).

Where exactly is the value of createBufferStrategy(3) stored?

It cannot be stored in bs.. so how does bs go from null to actually being initialized or holding a value when I only told my subclass to create a buffer strategy. I don't see how I changed the state of bs from null to whatever..

I tried to do bs = createBufferStrategy(3) and it doesn't work, obviously. I'd like to know why and how and what exactly is happening.

Thank you in advance.


Solution

  • From the JavaDocs

    public BufferStrategy getBufferStrategy()

    Returns the BufferStrategy used by this component. This method will return null if a BufferStrategy has not yet been created or has been disposed.

    By default, Canvas does not create or use any type of buffer strategy. In your code, when you call

    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
    

    You are checking to see if any previous buffer strategy has being create and is active (hasn't being disposed), this ensures that when ever this method is called, all attempts are made to provide a valid BufferStrategy

    When you call createBufferStrategy(3); it constructs a BufferStrategy internally to meet your requirements and assigns the results back to an internal instance variable, which is returned by calling getBufferStrategy

    You might try changing your code to something more like...

    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        createBufferStrategy(3);
        bs = this.getBufferStrategy();
    }
    
    if (bs == null) {
        // It might not be possible to create a buffer strategy for your hardware,
        // or the component is not attached to a native peer
    } else {
        // Start painting :D
    }