How to validate if Text entered is a numeric number?

本秂侑毒 提交于 2019-12-06 06:11:05

Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    float num1, num2, result;

    try {
        num1 = Float.parseFloat(jTextField1.getText());
        num2 = Float.parseFloat(jTextField2.getText());
        result = num1+num2;
        jTextField3.setText(String.valueOf(result));

    } catch (NumberFormatException e) {
        JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
    }
}
polygenelubricants

If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.

Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.

That said, you can, among other things, use Integer.parseInt(String s) to see if an arbitrary string can be parsed into an int; the method throws NumberFormatException if it can't. There are also Double.parseDouble, etc.

See also

Related questions

try {
    Integer.parseInt(foo);
} catch (NumberFormatException e) {
    // Naughty
}

Try this:

String temp = txtField.getText();
try 
  {
    int val = Integer.parseInt(temp);
  }
catch(NumberFormatException e) {
  System.out.println("Invalid");
 }

To make it more enjoyable, use JOptionPane (makes it more more interactive)

textFieldCrDays = new JTextField();
    textFieldCrDays.addKeyListener(new KeyAdapter() {
        //// validate onlu numeric value
        public void keyTyped(KeyEvent e) {
            if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
            {
                // Optional
                super.keyTyped(e);
            }
            else
            {
                // Discard the event
                e.consume();
            }
        }
    });
Jaymes Bearden

A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.

Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListener for the keyType event and check for the Char value. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers. You could also do a relative length here as well:

textField.addKeyListener(new KeyAdapter()
{
    @Override
    public void keyTyped(KeyEvent keyEvent)
    {
        if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
        {
            // Optional
            super.keyTyped(keyEvent);
        }
        else
        {
            // Discard the event
            keyEvent.consume();
        }
    }
});

You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example). A good place for this would be on the focusLost event(?).

If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.

EDIT: Using Character.isLetter(keyEvent.getKeyChar()) is even more clear.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!