Search code examples
javaswingkeyboard-shortcutsjtextfieldkeylistener

How to properly implement SHIFT + BACKSPACE key stroke inside of a JTextfield


So I have a basic swing application, it contains a JTextfield, I add the following KeyListener to it:

public class PromptKeyListener implements KeyListener {

    private boolean SHIFT_PRESSED;

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            //Do Thing A
        } else if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            this.SHIFT_PRESSED = true;
        }

                     if (SHIFT_PRESSED
                && e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            //Do Thing B
        }

       }

    @Override
    public void keyReleased(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            this.SHIFT_PRESSED = false;
        }
        System.out.println(SHIFT_PRESSED);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

}

The problem is when I press and hold SHIFT as well as Backspace Thing B does happen but the Backspace key does also remove a single character from the textbox as it normally does.

Is there a way to prevent Backspace from removing characters from the textbox when SHIFT is held down?


Solution

  • See Stopping default behavior of events in Swing

    That answer says you should be able to call

    e.consume()
    

    to prevent the default behavior of text going into the field.