Detecting backspace key press

1.1k views Asked by At

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);
    }
}
2

There are 2 answers

2
Eric Leibenguth On

Pressing the backspace key won't trigger the insertString() method. It should rather trigger the remove() 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:

public class KeyEventDemo implements KeyListener {

    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {}

    /** Handle the key-pressed event from the text field. */
    public void keyPressed(KeyEvent e) {}

    /** Handle the key-released event from the text field. */
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE){
             // Do something...
        }
    }

}
1
StanislavL On

As far as I know no way t detect that in DocumentFilter.

If you select a char and press DEL it's the same as you press BACKSPACE. Offset and length of deleted text is identical.

Instead you can define your KeyBinding for BACKSPACE processing and place your code there.