我正在使用Java,我的代码的这一部分用于在只接受数字,后退空格和删除的文本字段中输入年龄。如果代码是第一个字符,我怎么能告诉代码避免接受0?
谢谢。
以下是代码:
private void tfAgeKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if(!(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
}
答案 0 :(得分:1)
您只需要在当前输入为空时使用0
检查您输入的字符是否等于c == '0'
:
if((this.currentInput.isEmpty() && (!Character.isDigit(c) || c == '0')) || !(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
答案 1 :(得分:1)
private void tfAgeKeyTyped(final java.awt.event.KeyEvent evt) {
final char c = evt.getKeyChar();
// You need access to the current input to known if you are on the
// first character or not.
// Here I assume it exists as a private member variable.
final boolean isFirstChar = this.currentInput.isEmpty();
final boolean isValidEvent = (Character.isDigit(c) && !(isFirstChar && c == '0')) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE);
if (isValidEvent) {
evt.consume();
}
}