Michael Moretti Michael Moretti - 1 month ago 7
Java Question

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">
<MenuBar fx:id="menubar_mainmenu" />

And this is my Controller

public class ControllerMain {

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"));


After debugging I saw that the variable menubar_mainmenu is null

This is the error:
IntelliJ error

Thank you in advance for your help.


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"));