Search code examples
javaswingintjtextfieldjformattedtextfield

JTextField Validation with integers


I am trying to validate integer values from a JTextField. I want to make sure the user only enters integer values between a set range. I tried working with a JFormattedTextField but so far no luck.


Solution

  • One good option is to use an InputVerifier - your text field will not yield focus unless the input conditions are met. A JFormattedTextField won't do here since your restriction is not solely format, but also mathematical.

    public class NumRange extends JFrame {
    
        public static void main(String[] args) {
    
            new NumRange();
        }
    
        NumRange() {
    
            final int MIN = 0;
            final int MAX = 100;
    
            JTextField textField = new JTextField();
            textField.setInputVerifier(new InputVerifier() {
    
                @Override
                public boolean verify(JComponent input) {
                    String text = ((JTextField) input).getText();
                    int num;
                    try {
                        num = Integer.parseInt(text);
                    } catch (NumberFormatException e) {
                        return false;
                    }
                    if (num <= MAX && num >= MIN)
                        return true;
                    return false;
                }
            });
    
            getContentPane().add(textField);
            getContentPane().add(new JTextField(), BorderLayout.PAGE_END);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    }
    

    Try to switch focus to the bottom text field after entering various inputs to the top one.