JavaFX controller is always null

前端 未结 2 1364
渐次进展
渐次进展 2021-01-22 11:47

I\'ll try to get in JavaFX 2 and used a simple demo app. The Project consists of 3 Files, the Main.java, the Controller.java and the sample.fxml.

In Sample.fxml i declare

2条回答
  •  自闭症患者
    2021-01-22 12:05

    The FXMLLoader.load(URL) method is a static method. So when you execute

      FXMLLoader loader = new FXMLLoader();
      Parent root = loader.load(getClass().getResource("sample.fxml"));
    

    you are not loading the FXML file from the instance of the FXMLLoader that you constructed ("loader"). (You're actually invoking the static method through an object reference.) Hence the loader's controller never gets initialized.

    You need

      FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
      Parent root = loader.load();
    

    This constructs a loader with a location specified, and then the load() method, which is not a static method, is properly invoked on the FXMLLoader instance. Then

    System.out.println(loader.getController());
    

    will give the correct result.

提交回复
热议问题