【发布时间】:2023-04-02 09:46:01
【问题描述】:
更新 我要做的只是将标签的值保存到另一个类。这是我最大的问题,似乎没有任何效果。
我已经在 javafx 项目上工作了几个星期。我几乎完成了,但在课堂上交流信息时遇到了麻烦。 2天后,我仍然无法弄清楚为什么它不起作用。下面是一些代码:
我初始化数据的类:
@FXML
Label money;
@FXML
int holder;
@FXML
Label tst;
int currency;
BankData bank;
//this is where text for money label is set from user input
public void presetMoney(ActionEvent e) {
if(e.getSource() == ten) {
currency += 10;
money.setText(Integer.toString(currency));
}
//this is where I try to retrieve the value of money
public void testing() {
this.holder = Integer.parseInt(money.getText());
bank.storeData(holder);
tst.setText(Integer.toString(holder));
}
public int getTesting() {
return this.holder;
}
BankData.java(我试图设置数据的类):
String data;
public void storeData(String data) {
this.data = data;
}
当然,我得到了这个错误:
Caused by: java.lang.NullPointerException
at application.TransactionScreenController.testing(TransactionScreenController.java:159)
... 58 more
在我被重定向到一些 NullPointer 帖子并被否决之前,我只想知道为什么我的变量在尝试将其保存到另一个类时返回 null。显然,变量“holder”不为空,因为我通过将其设置为另一个标签对其进行了测试。
Here is a picture to help make it more clear
我成功地从 Label money 获取文本并将其设置为 int holder。然后我将 holder 的值设置为标签 tst。但是,当我尝试将 holder 的值设置为另一个类时,我得到一个空指针。
编辑 我初始化了 BankData bank = new BankData() 并尝试将变量更改为 int。我只得到 0 而不是 null。
EDIT 2 所以我尝试了 FXML 注入,现在我得到了一个类异常
public void trasComplete(ActionEvent e) throws IOException {
FXMLLoader loader = new FXMLLoader();
//methods to change screen not included because of irrelevance
BankData n = loader.getController();
n.storeData(holder);
}
Caused by: java.lang.ClassCastException: application.SecrurityScreenController cannot be cast to application.BankData
at application.TransactionScreenController.trasComplete(TransactionScreenController.java:173)
... 58 more
【问题讨论】:
-
是
FXML注入需要看吗? -
已编辑问题