如何避免这种NullPointerException

如何避免这种NullPointerException

本文介绍了如何避免这种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为null,但它在 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();

推荐答案

你在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:00