Thursday, February 28, 2013

Java Robot Class for Automatic Typing & Mouse Control

Java Robot 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.

     Now lets write a small java program, where we use robot class for automatic typing of "i am reni" in gedit and to move mouse pointer to Top-left corner.











//RobotClassDemo.java
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class RobotClassDemo{

        public static void main(String[] args) {
            
             try {
                 // using Runtime to open gedit
                 Runtime.getRuntime().exec("gedit");
               
                 Robot robot = new Robot();

                 // Creates the delay of 5 sec to open gedit
                 robot.delay(5000);
                
                // Then Robot start writing "i am reni"in gedit 
     
                 robot.keyPress(KeyEvent.VK_I);
                 robot.keyRelease(KeyEvent.VK_I);
                
                 robot.keyPress(KeyEvent.VK_SPACE);
                 robot.keyRelease(KeyEvent.VK_SPACE);
                
                 robot.keyPress(KeyEvent.VK_A);
                 robot.keyRelease(KeyEvent.VK_A);
                
                 robot.keyPress(KeyEvent.VK_M);
                 robot.keyRelease(KeyEvent.VK_M);
                
                 robot.keyPress(KeyEvent.VK_SPACE);
                 robot.keyRelease(KeyEvent.VK_SPACE);
                
                 robot.keyPress(KeyEvent.VK_R);
                 robot.keyRelease(KeyEvent.VK_R);
                
                 robot.keyPress(KeyEvent.VK_E);
                 robot.keyRelease(KeyEvent.VK_E);
                
                 robot.keyPress(KeyEvent.VK_N);
                 robot.keyRelease(KeyEvent.VK_N);
                
                 robot.keyPress(KeyEvent.VK_I);
                 robot.keyRelease(KeyEvent.VK_I);
                
                 // Robot moves mouse pointer to TOP-LEFT corner
                 robot.mouseMove(0, 0);
                  
             } catch (AWTException e) {
                 e.printStackTrace();
             } catch (IOException e) {
                e.printStackTrace();
            }
         }
     } 

Use following command to run RobotClassDemo.java

#javac RobotClassDemo.java
#java RobotClassDemo

No comments:

Post a Comment