Limit the Characters in the text field using document listner

前端 未结 1 1694
余生分开走
余生分开走 2020-12-21 11:24

How to limit the number of characters entered in a JTextField using DocumentListener?

Suppose I want to enter 30 characters max. After that

相关标签:
1条回答
  • 2020-12-21 11:33

    You'll want to use a DocumentFilter for this purpose. As the applies, it filters documents.

    Something like...

    public class SizeFilter extends DocumentFilter {
    
        private int maxCharacters;    
    
        public SizeFilter(int maxChars) {
            maxCharacters = maxChars;
        }
    
        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                throws BadLocationException {
    
            if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)
                super.insertString(fb, offs, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
        }
    
        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
                throws BadLocationException {
    
            if ((fb.getDocument().getLength() + str.length()
                    - length) <= maxCharacters)
                super.replace(fb, offs, length, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
        }
    }
    

    Create to MDP's Weblog

    0 讨论(0)
提交回复
热议问题