Michael Moretti Michael Moretti - 1 year ago 373
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.

Answer Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download