将JTextfield字符串解析为整数 [英] Parsing JTextfield String into Integer

查看:202
本文介绍了将JTextfield字符串解析为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我可以将StringJTextField转换为int.它说Exception in thread "main" java.lang.NumberFormatException: For input string: "".请帮忙.

So I have this to convert String from JTextField to int. It says Exception in thread "main" java.lang.NumberFormatException: For input string: "". Please help.

 JTextField amountfld = new JTextField(15);
 gbc.gridx = 1; // Probably not affecting anything
 gbc.gridy = 3; //
 add(amountfld, gbc);
 String amountString = amountfld.getText();
 int amount = Integer.parseInt(amountString);

推荐答案

来自

抛出:NumberFormatException-如果字符串不包含 可解析的整数.

Throws: NumberFormatException - if the string does not contain a parsable integer.

空字符串""不是可解析的整数,因此,如果未输入任何值,您的代码将始终生成NumberFormatException.

The empty String "" is not a parsable integer, so your code will always produce a NumberFormatException if no value is entered.

有很多方法可以避免这种情况.您可以简单地检查从amountField.getText()获得的String值是否确实被填充.您可以创建一个自定义IntegerField,该自定义IntegerField仅允许输入整数,但添加

There are many ways in which you can avoid this. You can simply check if the String value you got from amountField.getText() is actually populated. You can create a custom IntegerField, which only allows integers as input, but adding Document to a JTextField. Create a Document to only allow integers an input:

public static class IntegerDocument extends PlainDocument {

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        StringBuilder sb = new StringBuilder(str.length());
        for (char c:str.toCharArray()) {
            if (!Character.isDigit(c)) {
                sb.append(c);
            }
        }
        super.insertString(offs, sb.toString(), a);
    }
}

现在使用方便的getInt方法创建一个IntergerField,如果未输入任何内容,该方法将返回零:

Now create a IntergerField with a convenient getInt method, which returns zero if nothing is entered:

public static class IntegerField extends JTextField {
    public IntegerField(String txt) {
        super(txt);
        setDocument(new IntegerDocument());
    }

    public int getInt() {
        return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());        
    }
}

现在,您无需进行任何检查就可以从amountField检索整数值:

Now you can retrieve the integer value from amountField without doing any checks:

JTextField amountField = new IntegerField("15");
...
//amount will be zero if nothing is entered
int amount = amountField.getInt();

这篇关于将JTextfield字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆