Tuesday 11 March 2014

Small JAVA program to operate mouse from keyboard.

You can use all the functionality provided by mouse through keyboard.
I love JAVA and one of the reason is because it makes some complex tasks look very easy. I am going to use something called ROBOT class in java which is part of java.awt package.

Prerequisite knowledge:

  • Very basic java, if you have made 3-4 simple JAVA program than you should be fine.
    To see about ROBOT class's official documentation see here .
  • Should have java installed, I use eclipse IDE and I recommend it (It's free and opensource and really really awesome).

Difficulty of this tutorial:

Normal.

Lets get started:

First of all create a new java project and make the class which will have the function main() in it.
I named my class KeyboardAsMouse.java.
In the main function make a new instance of class robot class as:
Robot robot = new Robot();
Robot class has a function mouseMove(x,y), This function moves the pointer to (x,y) coordinate of the screen.

Taking Input:

I will use the arrow keys to take input and will use mouseMove(x,y) to move the mouse to x,y.
So, Input keys:
"Arrow keys"         To move the mouse
       "Space key"        For left click                 
"Control Key"         For right click

I am using a simple swing form to get input from keyboard, This can be done by using a KeyListener Like shown below:


Moving mouse:

To get current mouse position use following code:

Now all we have to do is move mouse, as I told earlier this can be done by robot.mouseMove() function. A case is shown below for up arrow:


Mouse clicks:

For mouse click use function robot.mousePress(KeyCode). But, here is a catch; see mousePress() but it will keep on pressing, so you have to apply mouseRelease() just after mousePress().

Putting this all together:


Thank You Guys, in case of any query or advise comment, feel free to mail me.
Fork this repository on Github

No comments:

Post a Comment