1

How do I detect the combination key Shift+Tab in a JTextField?

Sastrija
  • 3,284
  • 6
  • 47
  • 64
or123456
  • 2,091
  • 8
  • 28
  • 50
  • 1
    possible duplicate of [How can a KeyListener detect key combinations (e.g., ALT + 1 + 1)](http://stackoverflow.com/questions/7851505/how-can-a-keylistener-detect-key-combinations-e-g-alt-1-1) – jmj Dec 16 '11 at 13:38

3 Answers3

2

is this what you want?

javax.swing.JTextField textField = new javax.swing.JTextField();
textField.setFocusTraversalKeysEnabled(false);
javax.swing.Action myAction = new javax.swing.AbstractAction()
{
  public void actionPerformed(ActionEvent e)
  {
    //Insert arbitrary code here
  }
};
textField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, Event.SHIFT_MASK), "myCode");
textField.getActionMap().put("myCode", myAction);
Ky -
  • 30,724
  • 51
  • 192
  • 308
  • not use KeyListener this is wrong way, Swing JComponents are designated to use KeyBinding, only KeyBindings can override built-in key-shortcuts, only KeyBindings wokrs as you set, only KeyBindings ignore when JComponents has Fosus, or doesn't ignore, as you set – mKorbel Dec 17 '11 at 09:44
  • I've modified my example to use key bindings instead – Ky - Dec 17 '11 at 14:38
1

This is a bit of a special case since Shift+Tab is a focus traversal key. The focus subsystem normally consumes focus traversal keys, so you'll need to prevent that by calling

component.setFocusTraversalKeysEnabled(false);

on your JTextField. You'll then be able to detect the Shift+Tab combination and handle it yourself.

See How to Write a Key Listener for an example program you can download and experiment with to see how it works.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 2
    +1, for turning off forcus traversal. -1, for suggesting a KeyListener. Don't use a KeyListener. Swing was designed to use Key Binding. Read the section from the same tutorial on "How to Use Key Bindings". – camickr Dec 16 '11 at 16:52
1

Tab and Shift+Tab is only/by default (only KeyBinding can change that) about moving Focus from one JComponent to another, I think that you have to look at FocusListener with detailed descriptions in the FocusSubsystem, notice Focus came from Native OS and is by default asynchronous, most of time required delaying their actions/events wrapped into invokeLater()

Sastrija
  • 3,284
  • 6
  • 47
  • 64
mKorbel
  • 109,525
  • 20
  • 134
  • 319