gpt4 book ai didi

java - 在 Java 中验证整数值的问题

转载 作者:行者123 更新时间:2023-11-30 05:57:00 24 4
gpt4 key购买 nike

嗨,我正在使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com