1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.