John Dorian
John Dorian

Reputation: 1904

Creating a Hotkey in Java

I've been playing around with automation in java, since it's cross platform, kind of trying to create an autoit alternative for linux. Anyways I have this script working great, but I just want to be able to toggle an action with a hotkey.

I've seen the docs for key binding (http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), but either it isn't quite what I'm after or I'm misunderstanding the docs, in which case please forgive me and point me in the right direction.

My problem is that I don't have an GUI running, I have a java program that is moving my mouse to a new random position every 3 seconds. Here's my code:

public static void main(String[] args) {
        int[] screen = ScreenGetDim(); //get screen dimentions
        while (1==1) {
            int[] coordinates = new int[2]; //create an array for X and Y screen coordinates
            coordinates[0] = IntGetRandom( 0, screen[0] ); //get random X coordinate on screen
            coordinates[1] = IntGetRandom( 0, screen[1] ); //get random Y coordinate on screen
            MouseMove(coordinates[0], coordinates[1]); //move the mouse to screen coordinates
            Sleep(3000); //wait 3 seconds
        }
    }

This script works just like it should (ScreenGetDim(), IntGetRandom(), MouseMove(), and Sleep() are all functions that work perfectly and that I've defined elsewhere in the code).

My goal here is to be able to create a hotkey that could do something when I press it at any point during the runtime of my program.

For example, if I could set F11 as a hotkey that would do System.out.println("You pressed F11"); every time I press it that would be great. In AutoIt, for instance, one would just create a function that would do whatever you wanted to, let's call it Action(), and then you could simply do HotKeySet("{F11}", "Action") to make Action() run anytime you press F11. I'm looking for a Java equivalent.

Thanks for any help guys!

Upvotes: 2

Views: 6850

Answers (1)

epikfaal
epikfaal

Reputation: 25

I think what you are looking for event handling. You need to implement the interface KeyListener, this lets you create functions that get called whenever you press a button the function will look like this

         public void keyPressed(KeyEvent e) {
         switch (e.getKeyCode()) {
         //TODO list of all KeyCodes of events and code you want to execute(F11 keycode = 122)
         }
         }

after that you need to set the KeyListener to Listen to your Interface, Here it might get a bit tricky to help you since I don't know what kind of GUI you are using. When i used KeyListeners I used a Canvas, if you are using that it would look like this

        canvas.addKeyListener(this);

I hope this is what you are looking for

Upvotes: 1

Related Questions