问题
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
}
}
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?
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 ) {}
}
}
I said in that class's constructor that mc = new MC();
回答1:
You're calling dbg
on the this
instance, not the instance of render
.
You need to change it to
render.dbg.drawLine(....)
Alternatively, if you wanted to leave the dbg
call the same, you could call
this.gameRender();
first and then call
dbg.drawLine(...);
回答2:
You setup dbg
by invoking gameRender
on render
, but not this
.
回答3:
Since MC extends render, the dbg
you are referring to belongs to the MC instance that called draw. You can fix it by calling
render.dbg.drawLine( 100, 100, 200, 200 );
or take advantage of the inheritance you implemented
class MC extends Render {
//MC is a render, so you don't need to create another one
public void draw() {
gameRender(); //Call the MC's own gameRender
dbg.drawLine( 100, 100, 200, 200 ); //Calling gameRender initialized dbg so you won't get a NullPointerException
}
}
来源:https://stackoverflow.com/questions/11263199/how-to-avoid-this-nullpointerexception