Search code examples
javaswingjtextfielddefault-value

Constrain numeric value in JTextField to a specific range, with defaults


Not sure how to write this in JAVA... I need to code that will insert a default value (say 50) if user keys in a value outside of a given range of 10-100 feet. I have it working for errors if blank or non integer is entered or value is outside the range but cannot figure out how to integrate a default. What I have that works is

JPanel panel1 = new JPanel();
    panel1.setLayout(new FlowLayout());
    poolLength = new JTextField(10);
    panel1.add(new JLabel("Enter the pool's length (ft):"));
    panel1.add(poolLength);

What I want to add is something like this

If poolLength <10 or >200 then poolLength = 100
        Else this.add(panel1);

Solution

  • The simplest way is to get the text during e.g. an ActionEvent, parse it and reset the text if it's outside the range.

    jTextField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean isValid = true;
    
            try {
                int intVal = Integer.parseInt(jTextField.getText());
                if (intVal < 10 || intVal > 200) {
                    isValid = false;
                }
            } catch (NumberFormatException x) {
                // user entered something which is not an int
                isValid = false;
            }
    
            if (!isValid) {
                jTextField.setText("100");
            }
        }
    });
    

    Also see How to Use Text Fields.

    Another way would be to use a spinner which does something like this by default.