Detecting Tab Key Pressed Event in JTextField 's // Event.VK_TAB KeyPressed
Adding a KeyListener to a JTextField to detect KeyPressed events is pretty straightforward. But maybe you have encountered some problems when trying to detect special keys such as TABs. This issue is due to LowLevel keyEvents captured by Swing's default FocusTraversalKeys. What we need to do to capture the KeyEvent#VK_TAB
is to remove the default FocusTraversalKeys from the component.
1myJTextField.setFocusTraversalKeys(
2 KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
Once we've done this with the component, the tab KeyEvent will not be captured by swing's default focus traversal keys and we will be able to add events normally.
1myJTextField.addKeyListener(new java.awt.event.KeyAdapter() {
2 public void keyPressed (java.awt.event.KeyEvent evt){
3 if (evt.getKeyCode() == evt.VK_TAB) {
4 /* YOUR CODE GOES HERE */
5 doSomething();
6 /* If you want to change the focus to the next component */
7 nextJComponent.grabFocus();
8 }
9 }
10});
Comments in "Detecting Tab Key Pressed Event in JTextField 's // Event.VK_TAB KeyPressed"