难以理解的NullPointerException

时间:2015-01-10 08:11:28

标签: java nullpointerexception libgdx

我有一个非常基本的程序,应该显示标签和文本字段。我能够显示文字。对于textfield,我可以毫无错误地创建它,但当我将它添加到舞台并运行程序时,我有这个错误:

Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.scenes.scene2d.ui.TextField.draw(TextField.java:301)
at com.badlogic.gdx.scenes.scene2d.Group.drawChildren(Group.java:111)
at com.badlogic.gdx.scenes.scene2d.Group.draw(Group.java:58)
at com.badlogic.gdx.scenes.scene2d.Stage.draw(Stage.java:128)
at com.pace.converter.MainMenuScreen.render(MainMenuScreen.java:52)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.pace.converter.MyGdxGame.render(MyGdxGame.java:21)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

由于我不知道如何在我的评论的代码块中添加行号,因此以下是错误指向的行:

MainMenuScreen.java:52是

stage.draw();

MyGdxGame.java:21是

super.render();

我不明白为什么我有这个NullPointerException,因为我在将TextField添加到舞台之前创建了它。 这是我的完整代码:

主要活动:

public class MyGdxGame extends Game {
    SpriteBatch batch;
    AssetManager assets;

    @Override
    public void create () {
        batch = new SpriteBatch();
        assets = new AssetManager();

        this.setScreen(new LoadingScreen(this));
    }

    @Override
    public void render () {
        super.render();
    }

    public void dispose () {
        batch.dispose();
    }
}

主菜单屏幕:

public MainMenuScreen(final MyGdxGame gam) {
    game = gam;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    skin = new Skin(Gdx.files.internal("skin.json"));
    stage = new Stage();

    labelStyle = new LabelStyle(game.assets.get("font1.ttf", BitmapFont.class), Color.WHITE);
    labelTest = new Label("Test", labelStyle);
    textFieldTest = new TextField("Test", skin);

    stage.addActor(labelTest);
    stage.addActor(textFieldTest);
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.281f, 0.602f, 0.844f, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    game.batch.setProjectionMatrix(camera.combined);

    stage.act();
    stage.draw();
}

1 个答案:

答案 0 :(得分:0)

首先,您需要检查一些可能null的内容..将代码包装在try-catch块中 我不知道stage是什么,但检查它是否已被初始化?

如果stage不是null 然后检查Main menu Screen

skin = new Skin(Gdx.files.internal("skin.json")); // is the skin null ? if the file 'skin.json' couldn't be found then this would be null.. check this

textFieldTest = new TextField("Test", skin); // If skin is null, you're adding it here

至于super.render();它是否应该在这里调用?