我想将对象传递给我的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
请帮助,谢谢
答案 0 :(得分:1)
您需要在实例化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();
}
答案 1 :(得分:0)
1)在没有回调的情况下创建game_Implementation的对象。
2)使用它创建ICallbackTest的对象。 (在ICallbackTest构造函数中传递game_Implementation对象)
3)使用setter方法将回调对象传递给game_Implementation void setCallback(ICallbackTest a);
4)将game_Implementation对象传递给LwjglApplication构造函数。