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();
You're calling
dbg
on thethis
instance, not the instance ofrender
.You need to change it to
Alternatively, if you wanted to leave the
dbg
call the same, you could callfirst and then call
You setup
dbg
by invokinggameRender
onrender
, but notthis
.Since MC extends render, the
dbg
you are referring to belongs to the MC instance that called draw. You can fix it by callingor take advantage of the inheritance you implemented