【问题标题】:Limit the Characters in the text field using document listner使用文档侦听器限制文本字段中的字符
【发布时间】:2012-09-30 12:58:32
【问题描述】:

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

假设我想输入最多 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
    }
}
}

【问题讨论】:

  • 有比使用 DocumentListener 更简单的方法来实现这一点:stackoverflow.com/questions/3519151/…
  • 你为什么不简单地阅读教程?使用文本组件的章节第二页上有一个完整的示例...

标签: java swing jtextfield documentlistener documentfilter


【解决方案1】:

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

类似...

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's Weblog

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多