嗨,我正在使用Eclipse Rcp,我需要验证仅接受我使用代码的整数值的文本框
txtCapacity.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent EVT) {
if((EVT.character>='0' && EVT.character<='9')){
txtCapacity.setEditable(true);
txtCapacity.setEditable(true);
} else {
txtCapacity.setEditable(false);
System.out.println("enter only the numeric number");
}
}
});
它验证了,但这个问题是我无法使用退格键删除号码。请告诉我验证小数的想法。 提前致谢
最佳答案
不要使用KeyListener
!使用 VerifyListener
代替,因为这将处理粘贴、退格、替换......
例如
text.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
new BigDecimal(newS);
// value is decimal
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
关于java - 在 Java 中验证整数值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451894/