BlackCat
BlackCat

Reputation: 549

JavaFx-when fxml inject object field?

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? If so,how can i use a @fxml field immediately after i load a fxml(do not use lookup),just like this?(the code follow will throw a null exception)

    @FXML Label resultTF;
    ....
    FXMLLoader loader=new FXMLLoader();
    loader.setController(this);

    Parent pane = loader.load(getClass().getResource("/fxml/Main.fxml"));
    this.resultTF.setText("");

All i want to do is to declare a field with id in the fxml,and use it immediately after load the fxml,something like wpf,flex

Upvotes: 0

Views: 572

Answers (2)

Jonathan Rosenne
Jonathan Rosenne

Reputation: 2217

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.

Upvotes: -1

James_D
James_D

Reputation: 209330

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

Upvotes: 3

Related Questions