2017-10-14 57 views
0

我是最近刚接触javafx的人,我总是在控制器类的构造函数中加载fxml,然后直接使用组件。JavaFX FXML构造函数和初始化方法

我刚才了解到组件只能在调用initialize之前访问。

但是,即使我在构造函数中使用组件,也不会出现任何错误。 我的代码看起来像这样。

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


    } 

} 

没有零点例外occur.Why?

回答

1

所有public字段和与@FXML注释与匹配其中fx:idFXMLLoader在分配的控制器类进行初始化名非public字段(使用FXMLLoader.setController(Object))被调用的方法FXMLLoader.load()时。

所以可以假定(因为它不在你的问题包括在内)您在FXML文件Main.fxmlfx:id="historyLV"ListView。这就是为什么你没有得到NullPointerException