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