Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

java - Limit the Characters in the text field using document listner

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
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...