Limit characters in a text box using a list of documents

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

Suppose I want to enter a maximum of 30 characters. After that, no characters can be entered into it. I am using the following code:

 public class TextBox extends JTextField{ public TextBox() { super(); init(); } private void init() { TextBoxListener textListener = new TextBoxListener(); getDocument().addDocumentListener(textListener); } private class TextBoxListener implements DocumentListener { public TextBoxListener() { // TODO Auto-generated constructor stub } @Override public void insertUpdate(DocumentEvent e) { //TODO } @Override public void removeUpdate(DocumentEvent e) { //TODO } @Override public void changedUpdate(DocumentEvent e) { //TODO } } } 
+2
source share
1 answer

For this purpose you will need a DocumentFilter . As it is applied, 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 in MDP Weblog

+2
source

All Articles