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;
}