2

我正在创建一个自定义DocumentFilter.

但是,我必须在几个不同的组件上使用它。它们之间的唯一区别是字符限制,可以通过更改单个变量来更改。

问题是,我如何将该变量传递给DocumentFilter?

这是我的自定义DocumentFilter类(大部分代码已删除):

class DefaultDocFilter extends DocumentFilter
{   
    public void insertString(FilterBypass fb, int offs,
         String str, AttributeSet a) 
    {
        //do something with charLimit 
    }

    public void replace(FilterBypass fb, int offs, int length,
         String str, AttributeSet a)
    {
        //do something else with charLimit
    }
}

主要代码中的实现:

int charLimit = 40;
doc = (AbstractDocument) JTextArea.getDocument();
doc.setDocumentFilter(new DefaultDocFilter());

我如何传递charLimitDefaultDocFilter?

4

2 回答 2

4

将变量添加到您的子类。

class DefaultDocFilter extends DocumentFilter
{
    private final int charLimit;

    public DefaultDocFilter(int charLimit) {
        this.charLimit = charLimit;
    }

    public void insertString(FilterBypass fb, int offs,
         String str, AttributeSet a) 
    {
        //do something with charLimit 
    }

    public void replace(FilterBypass fb, int offs, int length,
         String str, AttributeSet a)
    {
        //do something else with charLimit
    }
}

然后,当您添加文档过滤器时,只需使用您的限制构造一个新过滤器:

textField.getDocument().setDocumentFilter(new DefaultDocFilter(20));
于 2012-09-13T17:05:40.577 回答
4

您可以简单地添加为成员变量:

class DefaultDocFilter extends DocumentFilter
{   
    private int charLimit = 40;

    public void insertString(FilterBypass fb, int offs,
         String str, AttributeSet a) 
    {
        //do something with charLimit 
    }

    public void replace(FilterBypass fb, int offs, int length,
         String str, AttributeSet a)
    {
        //do something else with charLimit
    }

    public int getCharLimit() {
        return charLimit;
    }

    public void setCharLimit(int charLimit) {
        this.charLimit = charLimit;
    }
}

然后:

doc.setCharLimit(charLimit);
于 2012-09-13T17:05:42.623 回答