2

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?

Sammy Guergachi
  • 1,986
  • 4
  • 26
  • 52

2 Answers2

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

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.

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • @kleopatra What? Is your comment directed to me? If not, don't comment under this answer, comment under the question. If it is for me, some explanation as to what the alternative is would be nice – Ruan Mendes Aug 21 '12 at 17:09
  • certainly it's directed to you (why else would I comment and downvote _your_ answer ;) You are experienced enough to search ... – kleopatra Aug 21 '12 at 20:50
  • @kleopatra I just don't care enough, I haven't written Java UI code in over 10 years, I just pointed the user to an existing answer with an example. Since you know more about good practices for Java UI code, it would be nice of you to point out why using keyListeners are bad – Ruan Mendes Aug 21 '12 at 22:20