JavaFX FXMLLoader getController NullPointerExcepti

2019-07-31 02:04发布

I have a project in school where I have to develop a program where you first can choose whether you want to save/read to/from a SQL DB or to save/read to/from XML.

I've made a GUI where you can choose between both methods.

The GUI closes after the user clicks on one of the buttons and the MainMenu GUI opens. Now I need to know in the MainMenuController what the user choose. I found online a Method to call the MainMenuController inside the first controller, with FXMLLoader.getController().

try {                       
    Stage stage = new Stage();
    FXMLLoader Loader = new FXMLLoader();
    Parent root = Loader.load(getClass().getResource("MainMenu.fxml"));

    MainMenuController mc = Loader.getController();
    mc.setSave("sql");

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}
catch (Exception e) {
    e.printStackTrace();
}

MainMenuController

public class MainMenuController {   
    private String save = null;

    public void setSave(String save) {
        this.save=save;
    }
    public String getSave() {
        return save;
    }
}

But when i try to access a method in MainMenuController I get a NullPointerException for

mc.setSave("sql")

2条回答
神经病院院长
2楼-- · 2019-07-31 02:39

First ,to understand this issue ,you should make some tricks to detect where is your problem.When you do :

 System.out.println(mc);

You will find the result is null.So you can not call setSave("sql") with null object,you got a null controller because your did not specify the location of your file,but you can change some lines to resolve your problem :

 try {
            Stage stage = new Stage();
            FXMLLoader fxm = new FXMLLoader(getClass().getResource("MainMenu.fxml"));

            Parent parent = (Parent) fxm.load();
            Scene scene = new Scene(parent);
            stage.setScene(scene);
            stage.show();
            FirstController mc = fxm.getController();
            System.out.println(mc);
            mc.setSave("sql");
        } catch (Exception e) {
            e.printStackTrace();
        }
查看更多
爷、活的狠高调
3楼-- · 2019-07-31 02:53

You are calling the static method FXMLLoader.load(URL). Because this is a static method, it has no effect on the state of the FXMLLoader instance you created; specifically the controller field is not set.

Instead, set the location on the FXMLLoader instance, and call the instance method load():

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("MainMenu.fxml"));
// or just FXMLLoader loader = new FXMLLoader(getClass().getResource("MainMenu.fxml"));

Parent root = loader.load();
查看更多
登录 后发表回答