@FXML Objects are null in initialize Method

2019-08-20 03:01发布

问题:

i have a (shortened) java FX Class:

public class MyReportController extends
    javafx.application.Application implements Initializable {

@FXML
private CustomTextField autoTextField;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {


    TextFields.bindAutoCompletion(autoTextField, ServiceLocator
            .getInstance().getMeasurementService()
            .getAllMeasurementNumbers());
}......

the initialzie method is called, but the autoTextField(and all other FXML components) is null.

The Application is started from another class with the main method. First i had the main Method in the controller class with the result, that the controller class was instantiated twice. I think my current problem is related to that.

回答1:

You have to have the same fx:id declarations in your FXML as property names to inject. So for example, in FXML, CustomField controll declaration should have fx:id=autoTextField. This way dependencies will be injnected upon initialization.

Second thing, please dont use controller class that extends Application. This has simply no purpose here. Start application from different class that controller, and the controller class instance will be automaticly created once by FXMLLoader



标签: javafx-8