miércoles, 6 junio 2007

Detecting Tab Key Pressed Event in JTextField 's // Event.VK_TAB KeyPressed

« Dynamic icons for your JComponents // Create an icon JButton with dynamic icons. | Main | Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements »

Adding a KeyListener to a JTextField to detect KeyPressed events is pretty straight forward. Buy maybe you have encountered some problems when trying to detect special key such as TAB's. This issue is due to LowLevel keyEvents captured by Swing's default FocusTraversalKeys. What we need to do to capture the VK_TAB KeyEvent is to remove the default FocusTraversalKeys from the component.

        myJTextField.setFocusTraversalKeys(
                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.

myJTextField.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
        if(evt.getKeyCode() == evt.VK_TAB){
            /* PUT YOUR STUFF HERE OR CALL A FUNCTION */
            doSomething();
            /* If you want to change the focus to the next component */
            nextJComponent.grabFocus();
    }
});

Technorati Tags:

Posted by admin at 12:50 PM in Java

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« June »
SunMonTueWedThuFriSat
     12
3456789
10111213141516
17181920212223
24252627282930