如何尝试使用jtextfield捕获异常?

问题描述 投票:1回答:2

我正在制作一个简单的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());
        }
    }
}

提前致谢

java swing exception-handling
2个回答
0
投票
//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();
}

希望有所帮助。问候。


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.