尝试在启动方法

时间:2019-08-22 15:34:31

标签: java nullpointerexception fxml

我正在尝试使用FXML构建迷宫。每个图块都应该是从JavaFX矩形继承的tile类。我的尝试是在JavaFX start()函数中调用controller.initializeMaze方法,该方法使用fx:id =“ maze”将图块添加到GridPane中。

主要JavaFX文件:

public class Main extends Application {
    Controller controller = new Controller();


    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("GUI.fxml"));
            Scene scene = new Scene(root,600,600);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            controller.initializeMaze();
            primaryStage.setScene(scene);
            primaryStage.show();
            controller.initializeMaze();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

FXML文件:

<BorderPane xmlns:fx="http://javafx.com/fxml/1" 
    fx:controller="application.Controller">
    <GridPane fx:id="maze"/>
</BorderPane>

控制器文件:

public class Controller {
    @FXML
    private GridPane maze;  
    @FXML
    public void initializeMaze() {
        System.out.println(maze);
        for (int row=0; row<11; row++) {
            for (int coll=0; coll<11; coll++) {
                maze.add(new Tile(), coll, row);
            }
        }
    }
}

当我打印出迷宫对象时,我也会得到null。但是我不知道为什么GridPane没有初始化。

0 个答案:

没有答案