1 回答

TA貢獻1895條經驗 獲得超7個贊
談到您的實際問題,我注意到您的代碼中存在三個問題。
關于您在 newCustomer() 方法中獲得的 NPE,您啟動了 FXMLLoader 實例但未加載它。因此 getController() 為 null。要解決此問題,您需要在調用 getController() 之前先調用 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.
}
然而,上述修復是無用的,因為您正在創建一個未被使用的 FXMLDocumentController 的新實例(如 @kleopatra 指定的)。您必須實際傳遞要與之通信的控制器實例。您需要在 NewCustomerController 中創建該控制器的實例變量并設置它。
@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 設置到 TableColumns 一次,而不是每次設置客戶時。您可以將這兩行移動到initialize() 方法。
@Override
public void initialize(URL url, ResourceBundle rb) {
? ? custname.setCellValueFactory(new PropertyValueFactory<>("name"));
? ? city.setCellValueFactory(new PropertyValueFactory<>("city"));
}
添加回答
舉報