我正在使用JavaFX來顯示我的遊戲中的視圖。初始化JavaFX視圖時的空指針
當我打電話,我MainApp
類中的方法的看法是加載:
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
對象存儲的一些信息和材料。控制器看起來如下:
public class GameViewController {
private MainApp mainApp;
@FXML
public void initialize() {
mainApp.getGame(). ... //do something else
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
我一直這樣做。當控制器被加載時,MainApp
對象被設置在控制器中,我可以使用它。但是現在當有任何mainApp.get...
被調用時,我會得到一個空指針。字段mainApp
爲空。我真的不知道這筆交易在這裏,因爲我說在其他項目中這樣工作。
這看起來像一個非常好的和簡單的解決方案。我想它比我在其他答案的評論中首先想到的更清晰的風格。謝謝你! – Master1114