LibGDX - 如何让我的按钮工作?

时间:2014-09-13 19:30:42

标签: libgdx

我是LibGDX的新手,我慢慢接受它。当我运行应用程序时,它只是因为错误而强制关闭。但我不确定问题是什么。这是我所拥有的按钮的代码。

@Override
public void show() {
    // Viewport Camera
    camera = new PerspectiveCamera();
    viewport = new ExtendViewport(800, 480, camera);

    stage = new Stage(new ExtendViewport(800, 840));
    Gdx.input.setInputProcessor(stage);

    skin = new Skin(atlas);
    atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack"));

    table = new Table(skin);
    table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    textButtonStyle = new TextButtonStyle();
    textButtonStyle.up = skin.getDrawable("button.up");
    textButtonStyle.down = skin.getDrawable("button.down");

    buttonPlay = new TextButton("Play", textButtonStyle);
    buttonPlay.setWidth((float) (Gdx.graphics.getWidth()/2.5));
    buttonPlay.setHeight(Gdx.graphics.getHeight()/6);
    buttonPlay.setPosition((Gdx.graphics.getWidth()/2-buttonPlay.getWidth()/2), (float) (Gdx.graphics.getHeight()-(buttonPlay.getHeight())*2.5));
    buttonPlay.toFront();

    stage.addActor(buttonPlay);
    table.debug();
    table.add(buttonPlay);

}

错误:

Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.badlogic.gdx.scenes.scene2d.ui.Skin.addRegions(Skin.java:102)
at com.badlogic.gdx.scenes.scene2d.ui.Skin.<init>(Skin.java:88)
at com.badlogic.gdx.screens.Menu.show(Menu.java:83)
at com.badlogic.gdx.Game.setScreen(Game.java:61)
at com.badlogic.gdx.screens.Splash.render(Splash.java:38)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.dakotapederson.slingshotsteve.SlingshotSteve.render(SlingshotSteve.java:29)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)

第75行是show()方法的地方。

1 个答案:

答案 0 :(得分:1)

你的问题是你在地图集初始化之前用地图集初始化你的皮肤,地图集是空指针。你做完了:

skin = new Skin(atlas); //Here atlas isn't loaded so exception occurs
atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack"));

应该是:

atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack")); // Load atlas first
skin = new Skin(atlas);