2016-09-17 178 views
0

我正在嘗試使用JavaFX和FXML文件,但當我在控制器中注入MenuBar時,出現了一些問題,編譯器給了我一個NullPointerException。我嘗試使用按鈕和文本框,它的工作原理。@FXML注入中的空指針異常

這是mycode的: FXML文件:`

<?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>` 

這是我的控制器

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



    } 
} 

調試我看到變量menubar_mainmenu爲空

這是錯誤後: IntelliJ error

非常感謝您的幫助。

+0

您是否試過評論將菜單添加到menu_mainmenu的位置?如果錯誤仍然存​​在,那不是問題。 –

回答

2

使您的FXML控制器執行Initializable。然後系統會提示您執行方法initialize(URL url, ResourceBundle resourceBundle)。在這種方法中,您可以確定menubar_mainmenu已初始化。您可以將現有的代碼移入該方法。

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

我還不明白爲什麼它沒有初始化,但它的工作原理,非常感謝。 –