Use of Robot Class

Programming in Java doesn’t have to be dull and boring. In fact, it’s possible to have lots of fun while programming in Java. Lets use the Robot class to write programs that are both fun and useful.
Added in JDK v 1.3 .
As Per Sun (now Oracle):
“This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.”
Lets Start the fun by Moving Mouse Pointer Programmatically.

package in.bibek;
import java.awt.Robot;

public class RobotTest {
	 	 public static void main(String[] args) throws Exception 
	 	 {
	            Robot robot = new Robot();	 
	            // SET THE MOUSE X Y POSITION
	            robot.mouseMove(200, 550);
	     }
	}

Ex 2: Right Click of Mouse

package in.bibek;
import java.awt.Robot;
import java.awt.event.InputEvent;

public class RobotTest {
	 	 public static void main(String[] args) throws Exception 
	 	 {
	            Robot robot = new Robot();	 
	            // RIGHT CLICK
	            robot.mousePress(InputEvent.BUTTON3_MASK);
	            robot.mouseRelease(InputEvent.BUTTON3_MASK);
	     }
	}

Lets Play With Keyboard Events
This sample code will show the use of Robot class to handle the keyboard events. If you run this code and open a notepad then this code will write hi budy in the notepad.

 
package in.bibek;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotTest {
	 	 public static void main(String[] args) throws AWTException 
	 	 {
	         Robot robot = new Robot();	 
	         // Creates the delay of 5 sec so that you can open notepad before 
	         // Robot start writing 
	         robot.delay(5000); 
	         robot.keyPress(KeyEvent.VK_H); 
	         robot.keyPress(KeyEvent.VK_I); 
	         robot.keyPress(KeyEvent.VK_SPACE); 
	         robot.keyPress(KeyEvent.VK_B); 
	         robot.keyPress(KeyEvent.VK_U); 
	         robot.keyPress(KeyEvent.VK_D); 
	         robot.keyPress(KeyEvent.VK_Y); 
	     }
	}

Now you have enough input to start playing with Robot Class, just google for more and have fun.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.