Java Reference
In-Depth Information
public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
int currentLength = doc.getLength();
String currentContent = doc.getText(0, currentLength);
String before = currentContent.substring(0, offset);
String after = currentContent.substring(length+offset, currentLength);
String newValue = before + (text == null ? "" : text) + after;
currentValue = checkInput(newValue, offset);
fb.replace(offset, length, text, attrs);
}
private int checkInput(String proposedValue, int offset)
throws BadLocationException {
int newValue = 0;
if (proposedValue.length() > 0) {
try {
newValue = Integer.parseInt(proposedValue);
} catch (NumberFormatException e) {
throw new BadLocationException(proposedValue, offset);
}
}
if ((minimum <= newValue) && (newValue <= maximum)) {
return newValue;
} else {
throw new BadLocationException(proposedValue, offset);
}
}
}
Figure 15-9 shows the numeric range filter in use.
Figure 15-9.
Using a Document that restricts input to a range of values
The sample program using the new
IntegerRangeDocumentFilter
follows in Listing 15-8.