Restricting a Java Text field to just a range of integers
This time I came across a slightly different way than extending the documentfilter.
That is I will write my own plain document here.
class IntegerRangeDocument extends PlainDocument {
int minimum, maximum;
int currentValue = 0;
public IntegerRangeDocument(int minimum, int maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
public int getValue() {
return currentValue;
}
public void insertString(int offset, String string, AttributeSet attributes)
throws BadLocationException {
if (string == null) {
return;
} else {
String newValue;
int length = getLength();
if (length == 0) {
newValue = string;
} else {
String currentContent = getText(0, length);
StringBuffer currentBuffer = new StringBuffer(currentContent);
currentBuffer.insert(offset, string);
newValue = currentBuffer.toString();
}
try {
currentValue = checkInput(newValue);
super.insertString(offset, string, attributes);
} catch (Exception exception) {
Toolkit.getDefaultToolkit().beep();
}
}
}
public void remove(int offset, int length) throws BadLocationException {
int currentLength = getLength();
String currentContent = getText(0, currentLength);
String before = currentContent.substring(0, offset);
String after = currentContent.substring(length + offset, currentLength);
String newValue = before + after;
try {
currentValue = checkInput(newValue);
super.remove(offset, length);
} catch (Exception exception) {
Toolkit.getDefaultToolkit().beep();
}
}
public int checkInput(String proposedValue) throws NumberFormatException {
int newValue = 0;
if (proposedValue.length() > 0) {
newValue = Integer.parseInt(proposedValue);
}
if ((minimum <= newValue) && (newValue <= maximum)) {
return newValue;
} else {
throw new NumberFormatException();
}
}
}
Now you can attach your text field with this plain document as below to achieve our requirement.
Document rangeOne = new IntegerRangeDocument(0, 255);
JTextField textFieldOne = new JTextField();
textFieldOne.setDocument(rangeOne);
0 comments: