java - try/catch block 在 Action 监听器中不起作用

标签 java user-interface try-catch actionlistener jtextfield

我正在为学校开发两个程序,一个是获取联系信息并将其保存到文本文件中,另一个是从文本文件中读取。一切都很完美,但我必须在接受输入的程序中添加一个 try/catch block ,以便它能够捕获年龄文本字段中的非数字条目。从昨天起我一直在尝试许多不同的方法来做到这一点,但没有任何效果。下面是代码。如果有人能给我指出正确的方向,我将非常感激,因为我觉得有些基本的东西我还没有到达这里。谢谢

  private class SaveData implements ActionListener{
    public void actionPerformed(ActionEvent e){

            String age1 = (String)ageField.getText();
            int age = Integer.parseInt(age1);

            try{
                int a = age;
            }
            catch(InputMismatchException e1){
                JOptionPane.showMessageDialog(null, "Please enter an     Integer");
            }

            String name = (String)nameField.getText();
            String email = (String)emailField.getText();
            String cell = (String)cellField.getText();  

            if(age>= 0 && age<=120){
                outputFile.println("Name: " + name);
                outputFile.println("Age: " + age);
                outputFile.println("Email: " + email);
                outputFile.println("Cell #: " +cell);
                outputFile.println("---------------------------");

                nameField.setText("");
                ageField.setText("");
                emailField.setText("");
                cellField.setText("");
            }
            else{
                JOptionPane.showMessageDialog(null, "You have entered an invalid age \n " +
                                        "Please enter an age between 0 and 120",
                                                "Age Entry Error",      JOptionPane.ERROR_MESSAGE);

                nameField.setText("");
                ageField.setText("");
                emailField.setText("");
                cellField.setText("");
            }//end else
        }//end actionperformed
    }//end actionlistener

最佳答案

只需在 try/catch block 中写下 int Age = Integer.parseInt(age1); 这些行并捕获 NumberFormatException 异常即可。

关于java - try/catch block 在 Action 监听器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822941/

相关文章:

python - 如何使用 tkinter.place()?

JavaScript catch 参数已定义

javascript - 如何在不使用 try/catch 的情况下捕获错误或在运行时使用 try/catch 包装代码?

尽管参数类型不同,Java 方法名称仍不明确

java - Web 应用程序的正确文件夹结构

java - 如果打开的文件不是 XML,则再次 showOpenDialog()

ios - 在 iOS 9 的一个 View Controller 上隐藏状态栏

javascript - 当您无法控制时如何规避同源策略错误

java - Optaplanner 和链接

java - 如何禁用 Javalin 日志记录