JavaFx-when fxml inject object field?

后端 未结 2 1832
我在风中等你
我在风中等你 2021-01-26 05:52

I\'m new to javaFx,and I have found only within the @fxml function and initialize function the @fxml field not be null otherwise the @fxml field will always be null,is it true?

相关标签:
2条回答
  • 2021-01-26 06:08

    You are calling the static FXMLLoader.load(URL) method.

    Since it's a static method, it knows nothing about the instance you are using to invoke it (which is bad practice anyway; your IDE should issue a warning about this). Specifically, it doesn't have a controller set.

    You need to invoke an instance load() method, e.g.

    FXMLLoader loader=new FXMLLoader();
    loader.setController(this);
    loader.setLocation(getClass().getResource("/fxml/Main.fxml"));
    
    Parent pane = loader.load();
    
    0 讨论(0)
  • 2021-01-26 06:17

    You can specify the controller in the FXML file. The FXMLLoader will initialize the variables in the controller. In that case there is not problem with your code. It is good practice to separate the controller from the main class.

    0 讨论(0)
提交回复
热议问题