在背景框架上使用 Java KeyListener

发布于 2024-10-18 01:49:47 字数 194 浏览 2 评论 0原文

我有一个包含 JScrollPane 的内容窗格,其中包含一个不可编辑的 JTextArea,我正在使用它(现在)简单地显示有关按下的键的信息(只是试图让此 KeyListener 工作)。

KeyListener 位于 JTextArea 上,选择框架时一切正常。但是,即使选择了另一个窗口,我也希望注册按键。有办法做到这一点吗?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夕色琉璃 2024-10-25 01:49:47

我过去这样做过,但我不记得具体是怎么做的。我认为这与此类似:

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

DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);

只需使用自定义代码修改 SysOut 即可。如果要阻止调度事件,该方法应返回 true 而不是 false。我还发现这个问题可能会解决您的问题。

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.

假装爱人 2024-10-25 01:49:47

如果您需要在以下情况下监听按键,请考虑使用按键绑定进行监听的组件没有焦点。另一方面,如果您尝试在另一个应用程序获得焦点时监听按键,那么您最好的选择是不要使用 Java,而是使用一种可以让您更接近操作系统的编程语言,例如C 或 C++。

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++.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文