Limiting Textfields in Java

后端 未结 4 593
暗喜
暗喜 2021-01-20 00:42

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

4条回答
  •  余生分开走
    2021-01-20 01:06

    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.

提交回复
热议问题