Reputation: 549
I'm new to javafx recently,and I always load fxml in the constructor of controller class then use components directly.
I have just learned that the components can only be accessed before initialize was called.
But it's very weird even i use component just in constructor there are no error occur. My code look like this.
@Override
public void start(Stage primaryStage){
new MainController(primaryStage,this);
}
public class MainController{
@FXML
private ListView<HistoryPlay> historyLV;
public MainController(Stage primaryStage, Main main) {
initFxml();
initView();
}
private void initFxml() {
FXMLLoader loader=new FXMLLoader();
loader.setController(this);
try {
loader.setLocation(new File("fxml\\Main.fxml").toURL());
loader.load();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void initView() {
historyLV.setCellFactory(param -> new HistoryListCell(MainController.this,main));
historyLV.setItems(main.getHistoryManager().getHistoryList());
}
}
There are no null point exception occur.Why?
Upvotes: 1
Views: 1060
Reputation: 1842
All public
fields and non-public
fields with the @FXML
annotation with names which match an fx:id
are initialized by the FXMLLoader
in your assigned controller class (using FXMLLoader.setController(Object)
) when the FXMLLoader.load()
method is invoked.
So it can be assumed (since it is not included in your question) that you have a ListView
in your FXML file Main.fxml
with fx:id="historyLV"
. This is why you do not get NullPointerException
.
Upvotes: 2