简体   繁体   中英

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错误

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_mainmenu is initialized. You can move your existing code into that method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM