tags:

views:

240

answers:

4

Is there a way to limit a textfield to only allow numbers 0-100, thereby excluding letters, symbols and such as well? I have found a way, but it is way more complicated than seems necessary.

A: 

you must implement and add a new DocumentListener to your textField.getDocument(). I found an implementation here.

Pierre
+5  A: 

I'd suggest you should go with a JSpinner in this case. Text fields are pretty complicated to work with in Swing since even the most basic single-line ones have a full-blown Document class behind them.

Joey
+10  A: 

If you must use a text field you should use a JFormattedTextField with a NumberFormatter. You can set the minimum and maximum values allowed on the NumberFormatter.

NumberFormatter nf = new NumberFormatter();
nf.setValueClass(Integer.class);
nf.setMinimum(new Integer(0));
nf.setMaximum(new Integer(100));

JFormattedTextField field = new JFormattedTextField(nf);

However, Johannes suggestion of using a JSpinner is also appropriate if it suits your use case.

Mark
Oh, that's a nice one. Didn't know that yet. +1 as this is actually a text field instead of a text field + scroll bar :-)
Joey
`JFormattedTextField ` also works well with `InputVerifier `: http://java.sun.com/javase/6/docs/api/javax/swing/InputVerifier.html
trashgod
Beautiful! Thank you so much!
Luke
+1  A: 

You can set a DocumentFilter of the PlainDocument used by the JTextField. The methods of the DocumentFilter will be called before the content of the Document is changed and can complement or ignore this changes:

    PlainDocument doc = new PlainDocument();
    doc.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
        throws BadLocationException {
            if (check(fb, offset, 0, text)) {
                fb.insertString(offset, text, attr);
            }
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {
            if (check(fb, offset, length, text)) {
                fb.replace(offset, length, text, attrs);
            }
        }
        // returns true for valid update
        private boolean check(FilterBypass fb, int offset, int i, String text) {
            // TODO this is just an example, should test if resulting string is valid
            return text.matches("[0-9]*");
        }
    });

    JTextField field = new JTextField();
    field.setDocument(doc);

in the above code you must complete the check method to match your requirements, eventually getting the text of the field and replacing/inserting the text to check the result.

Carlos Heuberger