我正在使用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...被调用时,我都会得到一个Nullpointer。字段mainApp为空。我真的不知道这笔交易是什么,因为正如我所说,这在其他项目中也是如此。

最佳答案

真的只是对fabian答案的扩展。我同意您应该自己创建控制器实例(如他所说,在FXML中删除fx:controller)。它使您可以将东西声明为final,否则将无法将其声明,并且避免了您在公共API中必须拥有大量不需要的setter。

您可能会将许多initialise代码移到构造函数中。如果通常直接修改任何JavaFX小部件,我通常只将代码放在initialise中。

它看起来像这样:

public void showGameView() {
    try {
        System.out.println(game.getPlayer().getCurrentRoom());
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/GameView.fxml"));
        loader.setController(new GameViewController(this));
        AnchorPane GameView = (AnchorPane) loader.load();
        rootLayout.setCenter(GameView);

    } catch (IOException e) {
        e.printStackTrace();
    }
}




public class GameViewController {

    private final MainApp mainApp;

    public GameViewController(MainApp mainApp)
    {
        this.mainApp = mainApp;
    }

    @FXML
    public void initialize() {
        mainApp.getGame().  ... //do something else
    }

07-26 02:52