My suggestion is that you could change the overridden insertString
and replace
methods so that it checks whether any "."
has been inserted earlier before this insert or replace and change the filter in a way that the 'period' would be replaced by a blank string if any subsequent time the period
character is inserted by the user. I have illustrated as below:
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException {
String regExp;
Document doc = fb.getDocument();
if(doc.getText(0, doc.getLength()).indexOf(".") == -1){
regExp = "[^0-9.]";
} else {
regExp = "[^0-9]";
}
fb.insertString(off, str.replaceAll(regExp, ""), attr);
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException {
String regExp;
Document doc = fb.getDocument();
if(doc.getText(0, doc.getLength()).indexOf(".") == -1){
regExp = "[^0-9.]";
} else {
regExp = "[^0-9]";
}
fb.replace(off, len, str.replaceAll(regExp, ""), attr);
}
The above code will only allow the 'period' to be inserted just once in the Document
to which this DocumentFilter
is set.