Search code examples
javaswinglimitjtextfield

Maximum value on JTextField


I want to have a JTextField in which you can only type numbers (integers and decimals), and you can only type numbers below 12345 and above 0. How would I do this? What I have right now:

    JTextField tf = new JTextField();

    final PlainDocument doc = new PlainDocument();
    doc.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            String s = doc.getText(0, offset) + string + doc.getText(offset, doc.getLength() - offset);
            try {
                if (Double.parseDouble(s) > 12345) {
                    fb.replace(0, 5, "12345", attr);
                }
            } catch (NumberFormatException e) {
                fb.insertString(offset, string.replaceAll("\\D++", ""), attr);
            }
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            String s = (doc.getText(0, offset) + text + doc.getText(offset, doc.getLength() - offset)).trim();
            try {
                if (Double.parseDouble(s) > 12345) {
                    fb.replace(0, 5, "12345", attrs);
                }
            } catch (NumberFormatException e) {
                fb.insertString(offset, text.replaceAll("\\D++", ""), attrs);
            }
        }

    });

    tf.setDocument(doc);

(This is then added to a JFrame window at BorderLayout.CENTER, with nothing else in it)

But it doesn't work (I can't type anything). What am I doing wrong?

Note: I would prefer to use something along the lines of the above approach (Using Documents) and not have to resort to something like JFomattedTextField, if possible.


Solution

  • But it doesn't work (I can't type anything).

    if (Double.parseDouble(s) > 12345) {
        fb.replace(0, 5, "12345", attrs);
    }
    

    If the value is > 12345 you update the document with a hardcoded value.

    But, if the value is < 12345 you don't do anything. You need to insert the typed character in the document, by invoking super.replace(...) or super.insertString().