将变量传递给DocumentFilter

时间:2012-09-13 17:02:47

标签: java swing jtextarea documentfilter

我正在创建自定义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());

如何将charLimit传递给DefaultDocFilter?

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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);