Question

I'm creating a custom DocumentFilter.

However, I have to use it on several different components. Only difference between them is character limit, which could be changed by changing a single variable.

The question is, how do I pass that variable to DocumentFilter?

This is my custom DocumentFilter class (most of the code removed):

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

Implementation in main code:

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

How do I pass charLimit to the DefaultDocFilter?

Was it helpful?

Solution

You could simply add as member variable:

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

then:

doc.setCharLimit(charLimit);

OTHER TIPS

Add the variable to your subclass.

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

Then when you add the document filter, just construct a new one with your limit:

textField.getDocument().setDocumentFilter(new DefaultDocFilter(20));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top