Java 在GUI中发生异常后,我应该去哪里?
这完全是一个初学者的问题,但我在概念上有点难以理解如何在JavaGUI中使用异常处理程序 我在事件侦听器上有以下代码,等待按下按钮。基本上,如果他们输入的不是整数,那么它就不能是客户ID,因此我有一个异常处理程序来检查它是否可以被解析为整数。如果不能,则会将错误消息放入标签中。但是,从那里我该怎么办?目前,它显然继续到finally块,并将CustomerID输入为0,因为它的初始值是0Java 在GUI中发生异常后,我应该去哪里?,java,swing,user-interface,Java,Swing,User Interface,这完全是一个初学者的问题,但我在概念上有点难以理解如何在JavaGUI中使用异常处理程序 我在事件侦听器上有以下代码,等待按下按钮。基本上,如果他们输入的不是整数,那么它就不能是客户ID,因此我有一个异常处理程序来检查它是否可以被解析为整数。如果不能,则会将错误消息放入标签中。但是,从那里我该怎么办?目前,它显然继续到finally块,并将CustomerID输入为0,因为它的初始值是0 private void jButton1ActionPerformed(java.awt.even
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块将始终执行,因此在抛出异常时也将执行