Is there a way to detect when the backspace key on the keyboard has been pressed, using a document filter? The following is an edited code extract from here
For Example
public class IntFilter extends DocumentFilter {
boolean trueFalse = true;
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
StringBuffer buffer = new StringBuffer(string);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isDigit(ch)) {
buffer.deleteCharAt(i);
trueFalse = false;
}
/*
else if (backspace pressed)
{
trueFalse = true;
}
*/
else{
trueFalse = true;
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) fb.remove(offset, length);
insertString(fb, offset, string, attr);
}
}
Pressing the backspace key won't trigger the
insertString()
method. It should rather trigger theremove()
method (only when text is actually removed, which is not the case when the caret is at the beginning of the text for example).But you can detect any keystroke using a
KeyListener
(doc). Here's how you would detect the backspace key: