gpt4 book ai didi

java - 在 GUI 中发生异常后我该去哪里?

转载 作者:行者123 更新时间:2023-11-29 04:14:41 25 4
gpt4 key购买 nike

完全是新手问题,但我在理解如何在 Java GUI 中使用异常处理程序时遇到一点概念上的困难。

我在事件监听器上有以下代码,等待按下按钮。基本上,如果他们输入的不是整数,那么它就不可能是客户 ID,因此我有一个异常处理程序来检查它是否可以解析为整数。如果不能,则它会将错误消息放入标签中。但是,我该怎么做呢?目前,它显然继续到 finally block 并将 CustomerID 输入为 0,因为这是它被初始化的样子。

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
int custID = 0;
String custName = "";
String custAddress = "";
String custEmail = "";
String custPhone = "";
try{
custID = Integer.parseInt(this.custIDField.getText());
}
catch (NumberFormatException e){
errorMess.setText("Not a valid customer ID");
}
finally{
custName = this.nameField.getText();
custAddress = this.addressField.getText();
custEmail = this.emailField.getText();
custPhone = this.phoneField.getText();
comp.addCust(custID, custName, custAddress,
custEmail, custPhone);
custListArea.append(custID + ": " +custName);
custListArea.append("\n");
addressField.setText(null);
emailField.setText(null);
phoneField.setText(null);
nameField.setText(null);
custIDField.setText(null);
}
}

处理此问题并让按钮事件处理程序返回等待正确输入的正确方法是什么?

最佳答案

你可以简单地做:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int custID = 0;
String custName = "";
String custAddress = "";
String custEmail = "";
String custPhone = "";
try {
custID = Integer.parseInt(this.custIDField.getText());

custName = this.nameField.getText();
custAddress = this.addressField.getText();
custEmail = this.emailField.getText();
custPhone = this.phoneField.getText();
comp.addCust(custID, custName, custAddress, custEmail, custPhone);
custListArea.append(custID + ": " + custName);
custListArea.append("\n");
addressField.setText(null);
emailField.setText(null);
phoneField.setText(null);
nameField.setText(null);
custIDField.setText(null);
} catch (NumberFormatException e) {
errorMess.setText("Not a valid customer ID");
}
}

如果在调用 parseInt 时出现 NumberFormatException,它将抛出异常,并且不会在将文本设置为字段的地方执行您的代码。如果没有异常,它将更新字段中的文本。

finally block 将始终执行,因此在抛出异常时也会执行。

关于java - 在 GUI 中发生异常后我该去哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53132345/

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