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);
From docs:
Throws: NumberFormatException - if the string does not contain a parsable integer.
The empty String ""
is not a parsable integer, so your code will always produce a NumberFormatException
if no value is entered.
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);
}
}
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());
}
}
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();