Reputation: 65
This section of code executes when the user presses a button, and it should change the scene. The controller of the new scene needs an instance of an object, so I thought of creating a setter method in the new controller class that accepts such object.
Though, when I loader.getController()
, this method seems to return null, which causes a NullPointerException to be thrown, as I use try to use that controller's set method.
The new controller is instantiated in the new root node in a FXML file.
Here's the code that should load the new scene from the FXML file and do what I said above:
try {
Stage stage = (Stage) anchorPane.getScene().getWindow();
FXMLLoader loader = new FXMLLoader();
Parent newRoot = loader.load(getClass().getResource("ViewRegistrazione.fxml"));
Scene newScene = new Scene(newRoot);
stage.setScene(newScene);
stage.setMinWidth(600);
stage.setMinHeight(400);
stage.setResizable(false);
ViewRegistrazioneController viewRegistrazioneController = loader.getController();
viewRegistrazioneController.setUser(c);
} catch (Exception e) {
e.printStackTrace();
}
Here's the line in the new FXML file that sets the controller:
<AnchorPane fx:id="anchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="EatAdvisor.clienti.ViewRegistrazioneController">
How can I avoid getting a NullPointerException at viewRegistrazioneController.setUser(c);
?
Upvotes: 0
Views: 928
Reputation: 209339
The FXMLLoader.load(URL)
method you are calling is a static method. Consequently, it cannot change the state of any FXMLLoader
instance (including loader
) and so the controller instance in loader
remains null
.
You need to set the location on the FXMLLoader
instance and then call the instance method loader.load()
taking no parameters. You can do this either by calling setLocation(...)
:
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("ViewRegistrazione.fxml"));
Parent newRoot = loader.load();
or by using the constructor that takes a URL
parameter:
FXMLLoader loader = new FXMLLoader(getClass().getResource("ViewRegistrazione.fxml"));
Parent newRoot = loader.load();
Upvotes: 3