0

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

user1071777
  • 1,307
  • 1
  • 15
  • 23
Evil Washing Machine
  • 1,293
  • 4
  • 18
  • 43
  • @JigarJoshi He wants to hook the keyboard, not press a key. He already said he could do key presses fine. – user1071777 Jul 14 '14 at 18:28
  • This will solve your problem: [global hotkey listener](http://stackoverflow.com/questions/79658/react-on-global-hotkey-in-a-java-program-on-windows-linux-mac) – kajacx Jul 14 '14 at 18:31

1 Answers1

2

As far as I know, there's no way to do this in straight 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. I've done something like this by writing an X event handler in C++ (for *nix based OS). Since key events in Java are per GUI component, there's no way to do this on a global scale. 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. (XGrabKey).

lordoku
  • 908
  • 8
  • 22
  • @kajacx's comment should get you what you want. As you can see, that ended up using a JNA based implementation to get to the OS layer. – lordoku Jul 14 '14 at 18:36