gpt4 book ai didi

java - 在文本字段上执行算术运算的事件监听器

转载 作者:行者123 更新时间:2023-12-01 17:48:15 24 4
gpt4 key购买 nike

我对代码块的执行感到困惑。我有 4 个文本字段,分别是数量价格增值税金额

我想向 pricequantity 文本字段添加一个事件监听器,以便每当我更改每个文本字段中的文本时,都会计算新的 vat新的 amount 值会自动显示在各自的文本字段中。

我正在考虑这样的事情:

    private void addEventListeners() {
txtInvoiceQuantity.textProperty().addListener((ChangeListener) (observable, oldVal, newVal) -> calculateVATAmount((String) oldVal, (String) newVal));
}

private void calculateVATAmount(String oldVal, String newVal) {
if (newVal.length() > oldVal.length()) {
if (txtInvoiceQuantity.getText().length() > 0 && txtInvoicePrice.getText().length() > 0) {
try {
double quantity = Double.parseDouble(newVal);
double price = Double.parseDouble(txtInvoicePrice.getText());
double vat = Double.parseDouble(lblVAT.getText()) / 100;
double vatamount = quantity * price * vat;
txtInvoiceVAT.setText(String.valueOf(vatamount));
double invoiceAmount = (price * quantity) + vatamount;
txtInvoiceAmount.setText(String.valueOf(invoiceAmount));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

我显然无法使用该事件,因为它位于 txtInvoiceQuantity 上。那么我如何更改 calculateVATAmount(oldVal,newVal) 以便它执行我想要的操作?

如何将 oldVal 考虑在内(以防用户按退格键)?

最佳答案

嗯,据我了解,您必须复制该代码块,因为您要从每个处理程序中的不同文本字段传递参数。

对于旧值的分解,只需删除 if(newVal.length() > oldVal.length()) {} 。它应该看起来像这样:

   private void quantityHandler(String oldVal, String newVal) {
if (txtInvoiceQuantity.getText().length() > 0 && txtInvoicePrice.getText().length() > 0) {
try {
double quantity = Double.parseDouble(newVal);
double price = Double.parseDouble(txtInvoicePrice.getText());
double vat = Double.parseDouble(lblVAT.getText()) / 100;
double vatamount = quantity * price * vat;
txtInvoiceVAT.setText(String.valueOf(round(vatamount,2)));
double invoiceAmount = (price * quantity) + vatamount;
txtInvoiceAmount.setText(String.valueOf(round(invoiceAmount,2)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void priceHandler(String oldVal, String newVal) {
if (txtInvoiceQuantity.getText().length() > 0 && txtInvoicePrice.getText().length() > 0) {
try {
double quantity = Double.parseDouble(txtInvoiceQuantity.getText());
double price = Double.parseDouble(newVal);
double vat = Double.parseDouble(lblVAT.getText()) / 100;
double vatamount = quantity * price * vat;
txtInvoiceVAT.setText(String.valueOf(round(vatamount,2)));
double invoiceAmount = (price * quantity) + vatamount;
txtInvoiceAmount.setText(String.valueOf(round(invoiceAmount,2)));
} catch (Exception e) {
e.printStackTrace();
}
}
}

由于您正在使用货币值,因此我找到了一种转换为指定小数位数的方法,请在此处找到它

Rounding to 2 decimal places

关于java - 在文本字段上执行算术运算的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com