You're basically ignoring the parameters that are passed to you and what they mean...
offset
is the offset within the document where the newtext
will be inserted...length
is the number of characters to be deleted
Now, if we use the length
within the if
statement, we start to see a difference. Basically, when you call setText
, the length
will be equal to the number of characters in the text field (as all the text is to be replaced)...
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws
BadLocationException {
if (isNumeric(text)) {
System.out.println(offset + "; " + length + "; " + text);
if (this.length > 0 &&
fb.getDocument().getLength() + text.length() - length > this.length) {
return;
}
super.replace(fb, offset, length, text, attrs);
}
}
You're also calling super.insertString(fb, offset, text, attrs);
in the replace
method, which isn't helpful either...
Update from comments
The problem you're facing with setText(null)
is to do with the fact that isNumeric
in your filter is returning false
for null
and empty ("") values, but these are actually valid in some contexts...
Now, you could alter the isNumeric
method, but that might adversely affect the other methods of the filter, instead, we should be place an additional condition in replace
to catch this case and deal with it appropriately...
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws
BadLocationException {
if (isNumeric(text)) {
System.out.println(offset + "; " + length + "; " + text);
if (this.length > 0 &&
fb.getDocument().getLength() + text.length() - length > this.length) {
return;
}
super.replace(fb, offset, length, text, attrs);
} else if (text == null || text.equals("")) {
super.replace(fb, offset, length, text, attrs);
}
}