0

I keep getting a Java.Lang.NullPointerException on this code:

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

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}

Can someone tell what I am doing wrong?

War10ck
  • 12,387
  • 7
  • 41
  • 54
swingBoris
  • 35
  • 6

4 Answers4

3

Even when you call this.createBufferStrategy(3); your bs variable remains unassigned.

You need to read it back after creating it:

if(bs == null){
    this.createBufferStrategy(3);
    bs = this.getBufferStrategy();
}

It is a good idea to add a check to make sure that after the call of createBufferStrategy you get back a non-null:

this.createBufferStrategy(3);
bs = this.getBufferStrategy();
if (bs == null) throw new IllegalStateException("Buffered structure is not created.");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You should try this:

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

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
  • 1
    [`createBufferStrategy` returns void](https://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#createBufferStrategy%28int%29). – Tom Nov 23 '14 at 20:57
1

You forget to assign the new BufferStrategy in case it was null to the to variable bs. Change it to

if (bs == null) {
    bs = this.createBufferStrategy(3); // in case it returns BufferStrategy.
    bs = this.getBufferStrategy(); // otherwise
}
Christian Hujer
  • 17,035
  • 5
  • 40
  • 47
0

owww i am so stupid i forgot to put return it should be this

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

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}
swingBoris
  • 35
  • 6