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

标签 java eclipse-rcp validation

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

相关文章:

java - 如何在textView中有很多文本但只显示其中的一部分

Java 如何迭代 double 组并四舍五入到最接近的整数

java - Eclipse Memory Analyzer - Leak Suspects Report 没有指向我的类 - 为什么?

eclipse - 如何使eclipse View 完全不可关闭?

javascript - 在我的日期验证中合并前导零

html - w3c 链接检查器中的损坏链接问题

python - 使用 Openpyxl 读取包含 DataValidation 的 excel 文件需要更多时间

java - Flash 范围是否没有竞争条件?

java - 按下 javafx 按钮时不执行

eclipse - (Eclipse RCP) 如何将输出重定向到控制台 View ?