Input restriction function sample source code of JTextField (Example Validation: numerical value from 1 to 30)

Caution

Change the values of lowerLimit and upperLimit and use them. No matter which character you type, you can only enter half-width numbers 1 to 30. It is better to create an inner class for DocumentFilter.

Source code

Example


JTextField textField = new JTextField();
((PlainDocument)textField.getDocument()).setDocumentFilter(new DocumentFilter() {
    /**
     *Limited to 1 to 30 when entering numbers
     * @param fb
     * @param offset Cursor position
     * @param length Number of replacement characters
     * @param text replacement string
     * @param attrs fb.getDocument().getDefaultRootElement().getAttributes()Same as
     */
    @Override 
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
      throws BadLocationException
        int lowerLimit = 1;
        int upperLimit = 30;

        int valueInput = 0;
        try {
            valueInput = Integer.parseInt(text);
        } catch(Exception ex) {
            //Input values other than numerical values cannot be entered
            return;
        }
        //If the input value is a full-width number, it is automatically converted to a half-width number.
        text = String.valueOf(valueInput);
        //When no character was originally entered
        if(fb.getDocument().getLength() == 0) {
            //Only 1 to 9 characters can be entered
            if(valueInput != 0) {
                super.insertString(fb, offset, text, attrs);
            }
            return;
        }

        //When characters were originally entered
        } else {
            //Calculation of the value after input
            String strAlready = fb.getDocument.getText(0, fb.getDocument().getLength());
            int valueAlready = Integer.parseInt(strAlready);
            int valueTotal = 0;
            if(offset == 0) {
                // Input Left
                valueTotal = (int) (valueInput * Math.pow(10, strAlready.length()) + valueAlready);
            } else if(offset == strAlready.length()) {
                // Input Right
                valueTotal = (int) (valueAlready * 10 + valueInput);
            } else {
                // Input Mid
                int valueLeft  = (int) ( Integer.parseInt(strAlready.substring(0, offset))
                                        * Math.pow(10, strAlready.length()-offset+1) );
                int valueAdd   = (int) ( valueInput * Math.pow(10, strAlready.length()-offset) );
                int valueRight = Integer.parseInt( strAlready.substring(offset, strAlready.length()) );
                valueTotal = valueLeft + valueAdd + valueRight;
            }
            //Limit input values from 1 to 30
            if(valueTotal > upperLimit) {
                //Value after input>Maximum value
                super.remove(fb, 0, strAlready.length()); //Delete all original characters
                if(valueInput != 0) {
                    super.insertString(fb, 0, String.valueOf(valueInput), attrs); //Input value setting
                } else {
                    super.insertString(fb, 0, String.valueOf(upperLimit), attrs); //Maximum value setting
                }
            } else if(valueTotal < lowerLimit) {
                super.replace(fb, 0, strAlready.length(), String.valueOf(lowerLimit), attrs); //Minimum value setting
            } else {
                super.replace(fb, offset, length, text, attrs); //Replace method processing call at the time of original value input
            }
        }
    }

    /**
     *When deleting a value, a value smaller than 1 cannot be entered.
     * @param fb
     * @param offset Cursor position
     * @param length Number of characters to delete
     */
    @Override 
    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
        int lowerLimit = 1;

        String strBefore = fb,getDocument.getText(0, fb.getDocument().getLength());
        String strAfter  = strBefore.substring(0, offset)
                           + strBefore.substring(offset+length, fb.getDocument().getLength());
        int afterValue = 0;
        try {
            afterValue = Integer.parseInt(strAfter);
        } catch(Exception ex) {
            //Since the input value is controlled, no error should occur.
        }
        //Cannot set value less than 1
        if(strAfter.length() == 0 || afterValue < lowerLimit) {
            //If no value is entered or a value smaller than the minimum value is set, the minimum value is set.
            super.replace(fb, 0, strBefore.length(), String.valueOf(lowerLimit), fb.getDocument().getDefaultRootElement().getAttributes());
        } else {
           //Remove method processing call when deleting the original value
           super.remove(fb, offset, length);
        }
    }
});

Why I wrote this

I didn't write it anywhere.

Recommended Posts

Input restriction function sample source code of JTextField (Example Validation: numerical value from 1 to 30)
[Java] Flow from source code to execution
Sample code to assign a value in a property file to a field of the expected type