开发者

Limiting Textfields in Java

开发者 https://www.devze.com 2022-12-17 23:01 出处:网络
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 开发者_运维技巧neces

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.


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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消