如何避免此 NullPointerException [英] How to avoid this NullPointerException
问题描述
我正在开发一款小型街机视频游戏,我希望使用双缓冲来改进动画效果.我有一个类应该绘制空白图像,另一个类应该绘制一条简单的线条.但是,我在应该绘制线条的线上不断收到 NullPointerException
I'm working on a small arcade video game, and I am looking to double buffer to improve animation. I have one class that's supposed to draw the blank image, and another class that's supposed to draw a simple line. However, I keep getting a NullPointerException on the line where the line is supposed to be drawn
class Render extends JPanel {
public int dbWidth = 500, dbHeight = 400;
public Image dbImage = null;
public Graphics dbg;
public void gameRender() {
if( dbImage == null )
dbImage = createImage( dbWidth, dbHeight );
dbg = dbImage.getGraphics();
dbg.setColor( Color.white );
dbg.fillRect( 0, 0, dbWidth, dbHeight );
}
}
class MC extends Render {
public Render render = new Render();
public void draw() {
render.gameRender();
dbg.drawLine( 100, 100, 200, 200 ); // line where NullPointerException occurs
}
}
我想是图形变量 dbg 为空,但它在 gameRender();
中获取了 dbImage.getGraphics();
的值;我该如何解决这个 NullPointerException?
I suppose it's the Graphics variable dbg that's null, but it gets the value of dbImage.getGraphics();
in gameRender();
How could I fix this NullPointerException?
我也在这样的另一个类中调用 draw() 方法
I am also calling the draw() method in another class like this
public void run() {
running = true;
while( running ) {
mc.draw();
try {
Thread.sleep( 50 );
}
catch( Exception e ) {}
}
}
我在那个类的构造函数中说过 mc = new MC();
I said in that class's constructor that mc = new MC();
推荐答案
您在 this
实例上调用 dbg
,而不是 render<的实例/代码>.
You're calling dbg
on the this
instance, not the instance of render
.
你需要把它改成
render.dbg.drawLine(....)
或者,如果您想让 dbg
调用保持不变,您可以调用
Alternatively, if you wanted to leave the dbg
call the same, you could call
this.gameRender();
先调用再调用
dbg.drawLine(...);
这篇关于如何避免此 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!