难以理解的 NullPointerException

Incomprehensible NullPointerException

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

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.run(LwjglApplication.java:114)

由于我不知道如何在我的注释代码块中放置行号,这里是错误指向的行:

MainMenuScreen.java: 52 是

stage.draw();

MyGdxGame.java: 21 是

super.render();

我不明白为什么在将 TextField 添加到舞台之前创建 TextField 时出现此 NullPointerException。 这是我的完整代码:

主要 activity :

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

首先,您需要检查一些可能 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(); 应该在这里调用吗?