Michael Moretti
Michael Moretti

Reputation: 257

Null pointer exception in @FXML Injection

I'm trying to work with JavaFX and FXML files, but something goes wrong when I inject the MenuBar in the controller, compiler gives me a NullPointerException. I tried with buttons and textfields and it works.

This is mycode: FXML file:`

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<VBox fx:controller="it.fedgiac.projectmanager.controller.ControllerMain" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <children>
      <MenuBar fx:id="menubar_mainmenu" />
   </children>
</VBox>`

And this is my Controller

public class ControllerMain {

@FXML
public MenuBar menubar_mainmenu;






public void generateView(Stage stage) throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("main_layout.fxml"));

    Scene scene = new Scene(root);

    stage.setTitle("Projects Manager");
    menubar_mainmenu.getMenus().add(new Menu("File"));
    stage.setScene(scene);
    stage.show();



    }
}

After debugging I saw that the variable menubar_mainmenu is null

This is the error: IntelliJ error

Thank you in advance for your help.

Upvotes: 0

Views: 1202

Answers (1)

Yoland Gao
Yoland Gao

Reputation: 437

Make your FXML Controller implement Initializable. You will then be prompted to implement the method initialize(URL url, ResourceBundle resourceBundle). In this method, you can be sure that the menubar_mainmenuis initialized. You can move your existing code into that method.

public void initialize(URL url, ResourceBundle resourceBundle){
    menubar_mainmenu.getMenus().add(new Menu("File"));
}

Upvotes: 2

Related Questions