JavaFX - 初始化控制器时组件为空

JavaFX - Components are null when initializing Controller

主要 class :

Parent root = FXMLLoader.load(getClass().getResource("../layouts/main_window.fxml"));
primaryStage.setTitle("IMGManager");
primaryStage.setScene(new Scene(root));
primaryStage.show();

FXML :

<VBox id="navigation" stylesheets="@../../css/center_panels.css" 
      xmlns="http://javafx.com/javafx/8" 
      xmlns:fx="http://javafx.com/fxml/1" 
      fx:controller="controllers.NavigationController">

  <!-- ... -->

  <!-- List -->
  <AnchorPane prefHeight="1500.0" prefWidth="492.0">
      <children>
          <ListView id="directories-list" 
                    fx:id="navigationList" 
                    prefHeight="500.0" ... />
      </children>
  </AnchorPane>

</VBox>

控制器:导航控制器

public class NavigationController implements Initializable {

    @FXML private ListView<String> navigationList;

    // ...

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        // Get Home Directory
        FileSystemView fsw = ...

        // Updates the information displayed in the Navigation panel.
        if (navigationList != null)
        {
            updateNavigationDisplay();
        }
    }

    // ...
}

嗨,我遇到的问题是:

1. )

Whenever I try to link a JavaFX component and a Controller variable, neither the Scene Builder nor Intellij makes the "connection" between the fx:id(s) and the variables in my Controllers.

I always get the nullPointerError in the initialization of my Controller, but I found a (troublesome) workaround : if (navigationList != null).

I noticed that my initialization method fires twice. Once with null components and the second time (magic), components are detected. So by adding if (navigationList != null), I don't get any errors on the first initialization and on the second I do cool stuffs.

2. )

I am unable to access a component located in another FXML file then the one linked with the Controller : nullPointer.

ex:

Controller1 <--linked with this, works well (on second init...) --> FXML1.fxml

Controller1 -- trying to access components in --> FXML2.fxml ( fails miserably)

EDIT:

By "trying to access components in another fxml file", I mean with a mouse click or something like that -> And surely Not during the initialization, as some fxml files are not loaded yet.

我搜索了很多答案并为此浪费了几个小时。大多数情况下,通过更正一些小的拼写错误、丢失的@FXML 标记或添加 Intializable 接口的正确实现等方式解决了类似的情况。

就我而言,我真的不明白。希望这只是一个拼写错误或一些小错误。

感谢您的回答

问题 1:您是直接在 main_window.fxml 中添加给定的 FXML 还是在 main_window.fxml 中包含此 FXML?

问题 2:要通过第一个 fxml 的控制器访问位于另一个 fxml 中的组件,请参考此 link: https://www.youtube.com/watch?v=NgubWgheboI

我遇到了同样的问题。:)

尝试在 fxml 文件中使用 fx:id= 而不是 id=。这个解决方案对我有用。