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"));
}
添加回答
举报