Search code examples
javajtextfieldkeylistenerkey-bindingsalt

Alt key is not properly working in JTextField


I am trying to use 'Alt' key to switch between two JTextField in Java. I have used the code:

private void GetAltKey(java.awt.event.KeyEvent evt) {
        if (evt.isAltDown()) {
            this.GetVectorDirect(true); //Select another JTextField
        }
}

Now, this type of code is working, but not properly. I need to press 'Alt' key twice to actually switch over. Not only for that key, it happens for all other keys - the immediately next key press is ignored, i.e., I need to type to press the same key twice.

What is a better way to do this?


Solution

  • This is happening because the first alt you are pressing is triggering the GetAltKey event (by the way, consider to change to getAltKey), note please that when this happen your alt key isn't down, so your evt.isAltDown() is returning false.

    The solution is simple, change your evt.isAltDown() method to evt.getKeyCode() == KeyEvent.VK_ALT.

    private void getAltKey(java.awt.event.KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ALT) {
            this.GetVectorDirect(true); //Select another JTextField
        }
    }
    

    I hope it helped. Cheers