2012-09-13 285 views
2

我正在創建一個自定義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()); 

我如何通過charLimitDefaultDocFilter?

回答

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