I have a content pan开发者_高级运维e 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.
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.
Look into using key bindings if you need to listen for keys when a component that's doing the listening doesn't have focus. If on the other hand, you're trying to listen to keys when another application has focus, then your best bet is to not use Java for this, but rather to use a programming language that allows you to get closer to the OS such as C or C++.
精彩评论