简体   繁体   English

在没有UI组件的情况下收听Java中的按键

[英]Listening to key presses in Java without a UI component

I am trying to write what can best be surmised as a script to click a button on a browser many times without stopping. 我正在尝试写出最好的脚本作为脚本来多次单击浏览器上的一个按钮而不会停止。 I can do key presses ad infinitum fine using the java.awt.Robot class but the problem I'm having is coding the correct activator/interruptor; 我可以使用java.awt.Robot类无限次地进行按键操作,但是我遇到的问题是编码正确的激活器/中断器。 I don't know how to make Java listen to keyboard commands (I want to start/stop when I press F3) without using a listener, which in turn needs to be added to a UI component, if I am not mistaken. 我不知道如何在不使用监听器的情况下使Java监听键盘命令(我想在按F3时启动/停止),如果我没有记错的话,又需要将其添加到UI组件中。 How do I do this? 我该怎么做呢? Currently I have: 目前我有:

    public static void main(String[] args) throws Exception
    {
       final Robot robot = new Robot();
            robot.delay(10000);
            while (true)
            {
                robot.mousePress(InputEvent.BUTTON1_MASK);
                robot.delay(1000);
                robot.mouseRelease(InputEvent.BUTTON1_MASK);
            }
     }   

I realize it's probably very simple in Jython or Groovy, but I am curios nonetheless. 我意识到在Jython或Groovy中这可能非常简单,但是我还是个好奇者。

As far as I know, there's no way to do this in straight Java. 据我所知,没有办法在纯Java中做到这一点。 Since keyboard commands are handled by the OS, the only way to get Java to do this is to write some low level JNI. 由于键盘命令由操作系统处理,因此让Java执行此操作的唯一方法是编写一些底层JNI。 I've done something like this by writing an X event handler in C++ (for *nix based OS). 我通过在C ++中编写一个X事件处理程序(针对基于* nix的OS)来完成类似的工作。 Since key events in Java are per GUI component, there's no way to do this on a global scale. 由于Java中的关键事件是每个GUI组件,因此无法在全球范围内进行。 When I wrote the X event handle, I had the challenge of dealing with the limitation that only a single application at a time can grab a key. 当我编写X事件句柄时,我面临着这样的挑战:一次只能有一个应用程序可以抓取一个密钥。 (XGrabKey). (XGrabKey)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM