为什么我一直得到Java.Lang.NullPointerException

时间:2014-11-23 20:50:35

标签: java game-loop

我在这段代码上不断收到Java.Lang.NullPointerException:

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

    Graphics g = bs.getDrawGraphics();

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

有人能说出我做错了吗?

4 个答案:

答案 0 :(得分:3)

即使您致电this.createBufferStrategy(3);,您的bs变量仍然未分配。

创建后需要先阅读它:

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

最好添加一个检查,以确保在调用createBufferStrategy之后你得到一个非空的:

this.createBufferStrategy(3);
bs = this.getBufferStrategy();
if (bs == null) throw new IllegalStateException("Buffered structure is not created.");

答案 1 :(得分:2)

你应该试试这个:

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();
}

答案 2 :(得分:1)

如果它是变量bs的null,你忘记分配新的BufferStrategy。将其更改为

if (bs == null) {
    bs = this.createBufferStrategy(3); // in case it returns BufferStrategy.
    bs = this.getBufferStrategy(); // otherwise
}

答案 3 :(得分:0)

owww我是如此愚蠢我忘了把它归还应该是这个

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

    Graphics g = bs.getDrawGraphics();

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