1 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
談到您的實(shí)際問題,我注意到您的代碼中存在三個(gè)問題。
關(guān)于您在 newCustomer() 方法中獲得的 NPE,您啟動(dòng)了 FXMLLoader 實(shí)例但未加載它。因此 getController() 為 null。要解決此問題,您需要在調(diào)用 getController() 之前先調(diào)用 load() 方法。
public void newCustomer(ActionEvent e) throws IOException {
? ? String name = cNameTextField.getText();
? ? String stringCity = custCityTextField.getText();
? ? Customer customer = new Customer(10, name, stringCity);
? ? FXMLLoader fXMLLoader = new FXMLLoader(getClass().getResource("/mytableview/FXMLDocument.fxml"));
? ? fXMLLoader.load(); // YOU ARE MISSING THIS LINE
? ? FXMLDocumentController fXMLDocumentController = fXMLLoader.<FXMLDocumentController>getController();
? ? fXMLDocumentController.inflateUI(customer); // Getting NPE at this line.
}
然而,上述修復(fù)是無用的,因?yàn)槟趧?chuàng)建一個(gè)未被使用的 FXMLDocumentController 的新實(shí)例(如 @kleopatra 指定的)。您必須實(shí)際傳遞要與之通信的控制器實(shí)例。您需要在 NewCustomerController 中創(chuàng)建該控制器的實(shí)例變量并設(shè)置它。
@FXML
private void handleButtonAction(ActionEvent event) throws IOException {
? ? FXMLLoader fXMLLoader = new FXMLLoader(getClass().getResource("/com/newcustomer/NewCustomer.fxml"));
? ? Parent parent = fXMLLoader.load();
? ? NewCustomerController controller = fXMLLoader.getController();
? ? controller.setFXMLDocumentController(this); // Pass this controller to NewCustomerController
? ? Stage stage = new Stage();
? ? Scene scene = new Scene(parent);
? ? stage.setScene(scene);
? ? stage.show();
}
NewCustomerController.java
private FXMLDocumentController fXMLDocumentController;
public void setFXMLDocumentController(FXMLDocumentController fXMLDocumentController) {
? ? this.fXMLDocumentController = fXMLDocumentController;
}
public void newCustomer(ActionEvent e) throws IOException {
? ? String name = cNameTextField.getText();
? ? String stringCity = custCityTextField.getText();
? ? Customer customer = new Customer(10, name, stringCity);
? ? fXMLDocumentController.inflateUI(customer);//You are passing to the currently loaded controller
}
最后,您只需將 CellValueFactory 設(shè)置到 TableColumns 一次,而不是每次設(shè)置客戶時(shí)。您可以將這兩行移動(dòng)到initialize() 方法。
@Override
public void initialize(URL url, ResourceBundle rb) {
? ? custname.setCellValueFactory(new PropertyValueFactory<>("name"));
? ? city.setCellValueFactory(new PropertyValueFactory<>("city"));
}
添加回答
舉報(bào)