Search code examples
javaswingjtextfieldkeyevent

Detect type of region when a key pressed event occurs in Java


I am creating a shortcut in my Java application. When a user hits G, a dialog pops up. However, I do not want this to happen when the user is typing in a text field. Is there a way I can detect the type of region when an key released event occurs so I can only make the dialog window popup when the user is not in a text field?

Thanks in advance.


Solution

  • You can use Window.getFocusOwner() to get the Component that has focus in your application, and then use an instanceof check.

    For instance:

        public void keyReleased(KeyEvent e)
        {
            if(e.getKeyCode() == KeyEvent.VK_G && !(myWindow.getFocusOwner() instanceof TextField))
            {
                showDialog();
            }
        }