-->

Problem with Validating the Integer Value in Java

2020-07-24 06:15发布

问题:

hi i am using Eclipse Rcp and i need to validate the textbox that only accept the integer value for that i have use the code

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

It validates But the Problem with this one is that i cannot use the Backspace key for deleteting the number. and please tell me idea for Validating the decimal too. thanks in advance

回答1:

As you are using a listener, you can empty the text field, instead of making it not-editable. You can do something like this, the snippet is based upon your code.

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

Or better if you use JFormattedTextField. I'm not sure if you have that in SWT, even if you don't then try to look for the similar.



回答2:

Dont use the KeyListener! Use a VerifyListener instead as this will handle paste, backspace, replace.....

E.g.

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


回答3:

Another possibility is to use the FormattedTextField-Widget from Nebular, see http://www.eclipse.org/nebula/widgets/formattedtext/formattedtext.php The advantage is that you only have to provide a pattern, there is no need to write your own listeners..



回答4:

You can use this function to validate if the number:

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

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

        return i;
    }

If the function returns a value less than zero, then it is not a valid positive number.



回答5:

For validating if a value is infact decimal or not, you can simply use -

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


回答6:

You should probably set a Document on your text box. You can implement a customer Document to filter for valid input to satisfy your requirements. Each time text is added or removed from your field, the Document will check if the overall input is valid.



回答7:

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