2

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

Suppose I want to enter 30 characters max. After that no characters can be entered into it. I use 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
    }
}
}
IvanRF
  • 7,115
  • 5
  • 47
  • 71
Nikhil
  • 2,857
  • 9
  • 34
  • 58
  • 2
    There's easier ways to achieve this than with a DocumentListener: http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield – FThompson Oct 10 '12 at 06:01
  • 1
    why-o-why don't you simply read the tutorial? A complete example is on the second page of the chapter using text components ... – kleopatra Oct 10 '12 at 07:35

1 Answers1

2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366