我想将对象传递到ApplicationListener的实现中,但是我一直在获取NullPointerExceptions,所以我可能做错了什么。
我在行上得到了异常:callback.onReady();
这是个例外(行号错误,因为我删除了import语句):
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.dewi.jones.game_Implementation.create(game_Implementation.java:56)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:144)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:131)
基本上,我希望在onCreate方法的末尾触发一个回调。
请帮忙
谢谢
这是我用于ApplicationListener实现的代码:
public class game_Implementation implements ApplicationListener {
ICallbackTest callback;
public game_Implementation(ICallbackTest callback) {
this.callback = callback;
}
@Override
public void create() {
// initialize stuff
// call the onReady method at the end of the create method, when
// everything has been initialized and created
callback.onReady();
}
public void sayHello() {
System.out.println("Hello, this game is ready");
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void render() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
这是我的桌面游戏类:
public class desktopGame {
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "game";
cfg.useGL20 = true;
cfg.width = 480;
cfg.height = 320;
ICallbackTest callback = null;
final game_Implementation gameInstance = new game_Implementation(
callback);
callback = new ICallbackTest() {
@Override
public void onReady() {
gameInstance.sayHello();
}
};
LwjglApplication game = new LwjglApplication(gameInstance, cfg);
}
}
根据@Mel Nicholso的建议
这是我尝试的解决方案:
ICallbackTest callback = null;
final game_Implementation gameInstance = null;
callback = new ICallbackTest() {
@Override
public void onReady() {
gameInstance.sayHello();
}
};
gameInstance = new game_Implementation(
callback);
LwjglApplication game = new LwjglApplication(gameInstance, cfg);
现在,我收到错误消息:
The final local variable gameInstance cannot be assigned. It must be blank and not using a compound assignment
请帮忙,谢谢
最佳答案
您需要在实例化game_Implementation之前而不是之后设置变量callback
。切换两行的顺序。
[编辑添加]您需要打破循环引用
static class MyGameCallback {
private MyGame game;
public void onReady() {
game.sayHello();
}
public void setGame(MyGame game) {
this.game = game;
}
}
public static void main(String arg[]) {
MyGameCallback mgc = new MyGameCallback();
MyGame game = new MyGame(mgc);
mgc.setGame(game);
game.whateverMakesMeReady();
}