2

如何限制在JTextField使用中输入的字符数DocumentListener

假设我想输入最多 30 个字符。之后就不能再输入字符了。我使用以下代码:

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
    }
}
}
4

1 回答 1

2

DocumentFilter为此,您需要使用 a 。应用时,它会过滤文档。

就像是...

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();
    }
}

创建到MDP 的博客

于 2012-10-10T06:03:35.703 回答