关于Java:使用文档侦听器限制文本字段中的字符

Limit the Characters in the text field using document listner

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

假设我最多输入30个字符。此后,不能输入任何字符。我使用以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
    }
}
}


您将为此目的使用DocumentFilter。如果适用,它将过滤文档。

有点像...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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的Weblog