private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {
获取 keyTyped 并将其传递给方法 validate。
if(!validate(evt.getKeyChar())){
Char 或 keytyped 不是有效的输入,所以让它消费吧。
evt.consume();
}
这限制了Decimal的输入,只能输入一个小数点;
if(evt.getKeyChar()==KeyEvent.VK_DECIMAL || evt.getKeyChar()==KeyEvent.VK_PERIOD){
获取文本字段中输入的整个字符串;
String field = textField.getText();
获取点的索引(。或小数/句点)。
如果 String 没有点或小数点,则 indexOf() 方法返回 -1。
int index = field.indexOf(".");
if(!(index==-1)){ //index is not equal to -1
evt.consume(); //consume
}
}
}
每次按键,都会调用此方法。
private boolean validate(char ch){
这确定字符是否具有与整数、小数点、退格或删除匹配的值。如果 char 是整数、小数、删除或退格,则返回 true,否则返回 false。
但是它不限制可以输入多少个小数点。
if(!(Character.isDigit(ch)
|| ch==KeyEvent.VK_BACKSPACE
|| ch==KeyEvent.VK_DELETE
|| ch==KeyEvent.VK_DECIMAL
|| ch==KeyEvent.VK_PERIOD)){
return false;
}
return true;
}
这里是完整的代码,我提供了一些cmets,希望对你有帮助。
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
}