Sammy Guergachi
Sammy Guergachi

Reputation: 2006

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?

Upvotes: 2

Views: 842

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347334

While the solution works, you are taking the wrong approach (IMHO).

You should be taking advantage of the KeyBindings API

InputMap im = field.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap am = field.getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, KeyEvent.SHIFT_DOWN_MASK), "DoThingB");
am.put("DoThingB", new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {

        System.out.println("Do Think B");

    }
});

Also, you shouldn't be using a KeyListener to trap the enter key, you should be using an ActionListener

Upvotes: 3

Ruan Mendes
Ruan Mendes

Reputation: 92324

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.

Upvotes: 2

Related Questions