JFrame靠近背景并聆听按键 [英] JFrame Close to Background and Listen to Keys

查看:89
本文介绍了JFrame靠近背景并聆听按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

JNativeHook .它是唯一的跨平台解决方案,它将比while (1) { GetAsyncKeyState(...); Sleep(5); }这样的轮询方法更快,更省力.JNativeHook的最大性能瓶颈是操作系统,而不是库.

As previously mentioned, use JNativeHook. It is the only cross-platform solution and it will be much faster and less intensive than a polling approach like while (1) { GetAsyncKeyState(...); Sleep(5); } The biggest performance bottleneck with JNativeHook is the OS, not the library.

  1. 在框架不可见的情况下,ActionListener还能工作吗?

除非框架具有焦点,否则它将无法工作,但是本机库将提供其他确实无法聚焦的事件,因此您可以通过从NativeInputEvent侦听器构造自己的ActionEvent使其工作.只需确保将库设置为使用Swing事件分派器即可,因为默认情况下不使用它!

It will not work unless the frame has focus, but the native library will provide other events that do fire out of focus, so you could make it work by fabricating your own ActionEvent's from the NativeInputEvent listeners. Just make sure you set the library to use the Swing event dispatcher as it does not by default!

  1. 如何聆听多次按键?我有个主意,但听起来并不可行.

多次按键"是什么意思?如果您指的是在按下某个键时自动重复,则可以通过在以自动重复率的间隔超过自动重复延迟后发送多个按键事件"来处理.如果该事件产生可打印的字符,您还会收到多个键键入"事件.释放键后,将调度单个键释放事件.如果您要同时表示一个键序列或多个键,则需要进行自己的跟踪或签入本机输入侦听器,但这应该是可能的.

What do you mean by "multiple key presses?" If you mean auto-repeat when a key is held down, that is handled by sending multiple Key Pressed events after the auto repeat delay is exceeded at an interval of the auto repeat rate. You many also receive multiple Key Typed events if that event produces a printable character. When the key is released, a single key release event will be dispatched. If you mean a sequence of keys or multiple keys at the same time, you will need to do your own tracking or checks in the native input listener, but it should be possible.

基本修饰符示例:请注意,JNativeHook库同时具有修饰符键的左右掩码.我假设您想使用左侧或右侧的组合,这会使操作变得更加复杂.

Basic Modifier Example: Note that JNativeHook library has both a left and right mask for the modifier keys. I assume you want to use a combination of either the left or the right which makes this a tad more complicated.

public void nativeKeyPressed(NativeKeyEvent e) {
    // If the keycode is L
    if (e.getKeyCode() == NativeKeyEvent.VK_L) {
        // We have a shift mask and a control mask for either the left or right key.
        if (e.getModifiers() & NativeInputEvent.SHIFT_MASK && e.getModifiers() & NativeInputEvent.CTRL_MASK) {
            // Make sure you don't have extra modifiers like the meta key.
            if (e.getModifiers() & ~(NativeInputEvent.SHIFT_MASK | NativeInputEvent.CTRL_MASK) == 0x00) {
                ....
            }
        }
    }
}

这篇关于JFrame靠近背景并聆听按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆