为什么我不断收到显示java.lang.NullPointerException
问题描述:
我不断收到这个代码显示java.lang.NullPointerException:为什么我不断收到显示java.lang.NullPointerException
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
}
Graphics g = bs.getDrawGraphics();
g.dispose();
bs.show();
}
谁能告诉我在做什么错?
答
你应该试试这个:
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();
}
答
即使你打电话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.");
答
您忘记将新的BufferStrategy指定为null
以指定给变量bs。将其更改为
if (bs == null) {
bs = this.createBufferStrategy(3); // in case it returns BufferStrategy.
bs = this.getBufferStrategy(); // otherwise
}
答
owww我很愚蠢的我忘了回应该是这样
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.dispose();
bs.show();
}
如果'bs'为空,你希望这个代码的某些部分,使之不为空? – user2357112 2014-11-23 20:52:08
this.createBufferStrategy(3); – swingBoris 2014-11-23 20:52:56
@swingBoris:你如何期待改变'bs'? – SLaks 2014-11-23 20:53:39