Im trying to to check whenever a user types a character into textbox if it is a number. If it is not it should immediately remove it from the textbox.
What happens is I type in the number 1 (or any number or character), and it removes the value from the textbox when it is obviously a number.
Here is the event I am using:
private void txtLengthAKeyReleased(java.awt.event.KeyEvent evt) {
removeLastChar(txtLengthA); //pass the textbox
}
Here is removeLastChar() method:
public static void removeLastChar(JTextField txt)
{
//Get string from text field
String str = txt.getText();
//Make sure length > 0
if( (str.length()) != 0)
{
//Get the last char of the string
String s = str.substring(str.length()-1, str.length()-1);
System.out.println(s); //test debug
//If not numeric (try/catch Double.parseDouble)
if(!isNumeric(s));
{
//Remove last char from the text box
str = str.substring(0, str.length()-1);
txt.setText(str);
}
}
}
Check if string is numeric:
isNumeric() function:
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
Using
KeyListenersto filter or modifyJTextComponetsis only going to end in tears.You should be using a
DocumentFilterCheck out Limit the Characters in the text field using document listner, Deleting last keystroke in JTextField if invalid and JTextField limiting character amount input and accepting numeric only for examples (especially the links from the answer in the last question)