validationJava中的整数值的问题

嗨,我正在使用Eclipse Rcp ,我需要validation只接受整数值的文本框,我已经使用了代码

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"); } } }); 

它validation但问题是我不能使用Backspace键来删除数字。 请告诉我validation小数的想法。 提前致谢

在使用侦听器时,可以清空文本字段,而不是使其不可编辑。 您可以执行类似的操作,该代码段基于您的代码。

 txtCapacity.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent EVT) { if(!(EVT.character>='0' && EVT.character<='9')){ txtCapabity.setText(""); } } }); 

或者更好,如果你使用JFormattedTextField 。 我不确定你是否在SWT中拥有它,即使你没有尝试寻找类似的东西。

不要使用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; } } }); 

另一种可能性是使用来自Nebular的FormattedTextField-Widget,参见http://www.eclipse.org/nebula/widgets/formattedtext/formattedtext.php 。优点是你只需要提供一个模式,没有必要写你自己的听众..

您可以使用此函数来validation数字是否:

     public static int validateInteger(String number)
     {
         int i = -1;

        尝试{
             i = Integer.parseInt(number);
         }
         catch(NumberFormatException nfe)
         {}
         catch(NullPointerException npe)
         {}

        回归我;
     }

如果函数返回的值小于零,则它不是有效的正数。

要validationvalue是否为十进制小数,您可以简单地使用 –

 try { new BigDecimal(value.toString()); // value is decimal } catch (NumberFormatException numberFormatException) { // value is not decimal } 

您应该在文本框中设置文档 。 您可以实施客户文档以过滤有效输入以满足您的要求。 每次在字段中添加或删除文本时,文档都会检查整体输入是否有效。

 txtfield.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { char c=evt.getKeyChar(); if(Character.isLetter(c)) { JOptionPane.showMessageDialog(null, "PLEASE ENTER A DIGIT", "INVALID NUMBER", JOptionPane.ERROR_MESSAGE); txtfield.setBackground(Color.PINK); txtfield.setText(""); String s = txtfield.getText(); if(s.length() == 0){ txtfield.setBackground(Color.PINK); } } else { txtfield.setBackground(Color.white); } } });