【问题标题】:how to try and catch exceptions with jtextfield?如何尝试使用 jtextfield 捕获异常?
【发布时间】:2019-02-20 16:29:49
【问题描述】:

我正在制作一个简单的 gui,用户必须输入 2 个随机数字字符串,当按下“完成”按钮时,它将输出这 2 个字符串。 但是如何使用 try-catch 方法做到这一点,以便用户只能使用数字,否则它会捕获异常?

这是我的代码:

import java.awt.event.*;
import javax.swing.*;

public class Panel extends JPanel 
{
    private JTextField field1;
    private JTextField field2;
    private JButton button1;
    private JLabel label1;
    private JLabel label2;

    public Panel() 
    {
        label1 = new JLabel("first string: ");
        label2 = new JLabel("second string: ");
        field1 = new JTextField(38);
        field2 = new JTextField(3);
        button1 = new JButton("done");

        ButtonP buttonP = new ButtonP();
        button1.addActionListener(buttonP);

        this.add(label1);
        this.add(field1);
        this.add(label2);
        this.add(field2);
        this.add(button1);
    }

    private class ButtonP implements ActionListener 
    {   
        public void actionPerformed(ActionEvent e)  
        {
            System.out.println("String 1 " + field1.getText() + " and string 2 " + field2.getText());
        }
    }
}

提前致谢

【问题讨论】:

  • 使用JSpinnerSpinnerNumberModel 代替文本字段可以避免任何异常处理的需要。

标签: java swing exception-handling


【解决方案1】:
//You save yor recieved string from textfield and try to convert it to an integer
//If is not convertable, it throws an exception and prints in console the error
String string1 = field1.getText();
int myInteger = 0;
try {
    myInteger = Integer.parseInt(string1);
} catch(Exception e){
    System.out.println("Invalid input. Not an integer");
    e.printStackTrace();
}

希望对您有所帮助。问候。

【讨论】:

  • 不建议使用Exception 类来捕获异常。请改用正确的异常类。在你的情况下NumberFormatException.
【解决方案2】:

这里有两个选择。第一个也是推荐的一个,是use a JFormattedTextField,以消除获得NumberFormatException的机会。此外,它更加用户友好。

第二个选项是捕捉NumberFormatException,当你捕捉到它时,向用户添加一种“错误”消息(不太友好)并告诉他给出正确的输入。然后,他误点击了一个字母,我们又回到了错误消息。

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2011-12-05
    • 2014-05-11
    • 2014-04-10
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多