如何在JavaFX中使用从另一个控制器发送的整数而不获得NumberFormatException



我使用以下代码将Product发送到另一个控制器:

@FXML
void onActionModifytProduct(ActionEvent event) throws IOException {
Product productSelected = productsTableView.getSelectionModel().getSelectedItem();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/view/ModifyProductMenu.fxml"));
loader.load();

ModifyProductMenuController MPController = loader.getController();
MPController.sendProduct(productSelected);

stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
Parent scene = loader.getRoot();
stage.setScene(new Scene(scene));
stage.show();
}

然后这就是我在另一个控制器中接收代码的方式:

public void sendProduct(Product product) {
idLbl.setText(String.valueOf(product.getId()));
modifyProductNameTxt.setText(product.getName());
modifyProductInvTxt.setText(String.valueOf(product.getStock()));
modifyProductPriceTxt.setText(String.valueOf(product.getPrice()));
modifyProductMinTxt.setText(String.valueOf(product.getMin()));
modifyProductMaxTxt.setText(String.valueOf(product.getMax()));
}

现在,我需要在初始化期间使用发送到Label idLbl的整数,但每次我尝试通过将类似int id = Integer.parseInt(idLbl.getText());的东西放在public void initialize(URL url, ResourceBundle rb) {下来使用它时,我都会得到一个java.lang.NumberFormatException,尽管我知道我实际上正在传递一个整数,因为我在同一控制器的另一部分使用它(只是在初始化期间没有(。有什么方法可以让我的程序在初始化期间读取这个整数吗?我已经做了一段时间了,所以任何帮助都将不胜感激!

好的initialize((方法就像你类中的构造函数,所以它会首先被调用。你在它之后调用sendProduct((,所以在它之后会将值设置为idLbl。所以在调用initialize方法的过程中,你的值仍然是空的这就是它向你抛出NumberFormatExcpetion的原因。

最新更新