我正在使用 JavaFX 来显示我的游戏的 View 。
当我在我的 MainApp
类中调用方法时加载 View :
public class MainApp extends Application {
//fields
public MainApp() {
this.game = new Game();
}
//lots of other methods
public void showGameView() {
try {
System.out.println(game.getPlayer().getCurrentRoom());
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/GameView.fxml"));
AnchorPane GameView = (AnchorPane) loader.load();
rootLayout.setCenter(GameView);
GameViewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public Game getGame() {
return game;
}
Game
对象存储一些信息和东西。 Controller 如下所示:
public class GameViewController {
private MainApp mainApp;
@FXML
public void initialize() {
mainApp.getGame(). ... //do something else
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
我一直都是这样做的。加载 Controller 时,MainApp
对象会在 Controller 中设置,我可以使用它。但是现在,当任何 mainApp.get...
被调用时,我都会得到一个 Nullpointer。字段 mainApp
为空。我真的不知道这里的交易是什么,因为正如我所说,它在其他项目中也是如此。
最佳答案
Controller 类的 initialize
方法在 FXMLLoader.load
方法调用结束时被调用,即在您执行之前
controller.setMainApp(this);
这意味着此时 mainApp
字段仍然包含 null
。
您必须将取消引用 mainApp
的代码从 initialize
方法移动到 setMainApp
方法,使用初始化的 创建 Controller 实例mainApp
属性并在加载之前将其传递给 FXMLLoader
(需要删除 fx:controller
属性)或使用 Controller 工厂初始化 Controller 实例(这可能是最复杂的选项)。
关于java - JavaFX View 初始化时的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978995/