Search code examples
javaswingeventskey-bindingskeylistener

Use a Java KeyListener on a background frame


I have a content pane containing a JScrollPane wrapped around a non-editable JTextArea that I'm using to (right now) simply display info about what key is being pressed (was just trying to get this KeyListener to work).

The KeyListener is on the JTextArea and everything works fine when the frame is selected. However, I'd like for the key presses to be registered even if another window is selected. Any way to do this?

Thanks.


Solution

  • I did that in the past but I do not remember exactly how. I think it was similar to that:

    KeyEventDispatcher dispatcher = new KeyEventDispatcher()
    {
        public boolean dispatchKeyEvent(KeyEvent e)
        {
            System.out.println(e.getKeyChar());
            return false;
        }
    };
    
    DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
    

    Just modify the SysOut with your custom code. If you want to prevent an event from being dispatched, the method should return true instead of false. I also found this question that may adress your problem.