Reputation: 697
I have a class FontInfo and i try to send its object myFont to new controller of stage which appear when i click button. Here is my main controller class:
public class MainController {
//create instance of font
private FontInfo myFont;
@FXML
private Button btnChooseFont;
public void initialize()
{
//create new myFont
myFont = new FontInfo();
}
@FXML
void actionBtnChooseFont(ActionEvent event) {
try
{
//resource to new parent root
Parent root = FXMLLoader.load(getClass().getResource("../fxml/ChooseFont.fxml"));
Stage stage = new Stage();
stage.setTitle("Choose font");
stage.setScene(new Scene(root, 300, 290));
stage.show();
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("../fxml/ChooseFont.fxml"));
ChooseFontController chooseFontController = loader.getController();
chooseFontController.setMyFont(myFont);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I need to use myFont object which I create in MainConroller in ChooseFontController class :
public class ChooseFontController {
//myFont object
private FontInfo myFont;
//setter myFont
public void setMyFont(FontInfo myFont) {
this.myFont = myFont;
}
But i get null pointer exception error :
Caused by: java.lang.NullPointerException
at controllers.MainController.actionBtnChooseFont(MainController.java:48)
in :chooseFontController.setMyFont(myFont);
Can anyone help me with this issue ?
Upvotes: 1
Views: 346
Reputation: 1918
It seems like the FXMLLoader couldn't find a Controller, and therefore returns null from the loader.getController()
. Maybe calling loader.load()
helps finding it... e.g.
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("../fxml/ChooseFont.fxml"));
Loader.load();
ChooseFontController chooseFontController = loader.getController();
chooseFontController.setMyFont(myFont);
(Ps. Debugging helps a lot in these cases to find the exact problem)
Upvotes: 1
Reputation: 7255
Modify initialize method
:
@FXML
public void initialize()
{
//create new myFont
myFont = new FontInfo();
}
Actually the problem is that you never load the ChooseFont.fxml
document so you have to edit your code to load the fxml document:
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("../fxml/ChooseFont.fxml"));
try{
loader.load();
}catch(Exception ex){
ex.printStackTrace();
}
ChooseFontController chooseFontController = loader.getController();
Also keep in mind that here you are using a static constructor
Parent root = FXMLLoader.load(getClass().getResource("../fxml/ChooseFont.fxml"));
Upvotes: 1