I am trying to replace the text in a text box that has been filtered to only accept characters 0 to 9. I'm using String's here because I need the 0's to remain as part of the value. ex the first value would be 001 so it must be replaced by 002. It seems to work when I don't require a filter that forces numbers only. The initial check works - I'm able to type in 001 but then I submit 001 doesn't change to 002. Any help would be great.
THE CODE TRYING TO REPLACE THE TEXT ...
`if(pageBox.isSelected()){
String num;
System.out.println(newPage);
int p = Integer.parseInt(newPage);
p++;
if(p < 10){
num = ("00" + Integer.toString(p));
}
else if(p >= 10 && p < 100){
num = ("0" + String.valueOf(p));
}
else{
num = (String.valueOf(p));
}
pageField.setText(num);
}
else{
pageField.setText("");
}`
THE FILTER I'M USING //SETS CHARACTER LIMIT & ALLOWS NUMERIC VALUES ONLY
`class SizeAndStringNumFilter extends DocumentFilter {
private int limit;
public SizeAndStringNumFilter(int limit) {
this.limit = limit;
}
@Override
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offs, str);
if (test(sb.toString())) {
if ((fb.getDocument().getLength() + str.length()) <= limit)
super.insertString(fb, offs, str, a);
else
Toolkit.getDefaultToolkit().beep();
}
else {
//WARN - only numeric values allowed
}
}
private boolean test(String text) {
int i = text.length() - 1;
boolean check = text.charAt(i) >= '0' && text.charAt(i) <= '9';
if(!check){
//WARN USER
Toolkit.getDefaultToolkit().beep();
}
return check;
}
@Override
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offs, str);
if (test(sb.toString())) {
if ((fb.getDocument().getLength() + str.length()) <= limit)
super.insertString(fb, offs, str.toUpperCase(), a);
else
Toolkit.getDefaultToolkit().beep();
}
else {
//WARN - only numeric values allowed
}
}
}`
**EDIT I've found the culprit - The document filter doesn't replace the text it appends it. Not sure how to combat this
**EDIT2 Problem solved, once I figured out the issue I just had to add a second if statement for > limit if((fb.getDocument().getLength() + str.length()) - length > limit) super.replace(fb, offs, length, str.substring(0, limit-fb.getDocument().getLength()).toUpperCase(), a);