private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {
Get the keyTyped and pass it to the method validate.
if(!validate(evt.getKeyChar())){
Char or keytyped is not a valid input, so let it consumed.
evt.consume();
}
this limit the input of Decimal, only ONE decimal point can be entered;
if(evt.getKeyChar()==KeyEvent.VK_DECIMAL || evt.getKeyChar()==KeyEvent.VK_PERIOD){
get the whole string entered in the textField;
String field = textField.getText();
get index of dot(. or decimal/period).
indexOf() method returns -1 if String does not have any dot or decimal poits.
int index = field.indexOf(".");
if(!(index==-1)){ //index is not equal to -1
evt.consume(); //consume
}
}
}
Every keypress, this method gets called.
private boolean validate(char ch){
this determine if the character has matching value to Integer, Decimal point, backspace or delete. It returns true if the char is a integer, decimal, delete or backspace, otherwise false.
However it does not limit how many decimal points can be entered.
if(!(Character.isDigit(ch)
|| ch==KeyEvent.VK_BACKSPACE
|| ch==KeyEvent.VK_DELETE
|| ch==KeyEvent.VK_DECIMAL
|| ch==KeyEvent.VK_PERIOD)){
return false;
}
return true;
}
here is the whole code, I have provided some comments, hope these will help.
private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {
if(!validate(evt.getKeyChar())){ //get char or keytyped
evt.consume();
}
//limit one dot or decimal point can be entered
if(evt.getKeyChar()==KeyEvent.VK_DECIMAL || evt.getKeyChar()==KeyEvent.VK_PERIOD){
String field = textField.getText(); //get the string in textField
int index = field.indexOf("."); //find the index of dot(.) or decimal point
if(!(index==-1)){ //if there is any
evt.consume(); //consume the keytyped. this prevents the keytyped from appearing on the textfield;
}
}
}
//determine if keytyped is a valid input
private boolean validate(char ch){
if(!(Character.isDigit(ch)
|| ch==KeyEvent.VK_BACKSPACE
|| ch==KeyEvent.VK_DELETE
|| ch==KeyEvent.VK_DECIMAL
|| ch==KeyEvent.VK_PERIOD
)){
return false; //return false, because char is invalid
}
return true; // return true, when the if statement above does not meet its conditions
}