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")
First ,to understand this issue ,you should make some tricks to detect where is your problem.When you do :
You will find the result is
null
.So you can not callsetSave("sql")
withnull
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 :You are calling the static method
FXMLLoader.load(URL)
. Because this is a static method, it has no effect on the state of theFXMLLoader
instance you created; specifically the controller field is not set.Instead, set the location on the
FXMLLoader
instance, and call the instance methodload()
: