Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid this 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
    }
}

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

like image 522
kullalok Avatar asked Nov 29 '25 04:11

kullalok


2 Answers

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(...);
like image 96
Chris Thompson Avatar answered Dec 01 '25 17:12

Chris Thompson


You setup dbg by invoking gameRender on render, but not this.

like image 43
sudocode Avatar answered Dec 01 '25 16:12

sudocode