Sunday, September 25, 2011

Robot Class in java

Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.

This sample code will show the use of Robot class to handle the keyboard events. 

 RobotExp.java
-----------------------
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotExp {
   
    public static void main(String[] args) {
 
        try {
         
            Robot robot = new Robot();
           
            // Robot start writting(This Robot is Controlled by KIRAN)
            robot.delay(5000);
            robot.keyPress(KeyEvent.VK_H);
            robot.keyPress(KeyEvent.VK_I);
            robot.keyPress(KeyEvent.VK_SPACE);
            robot.keyPress(KeyEvent.VK_K);
            robot.keyPress(KeyEvent.VK_I);
            robot.keyPress(KeyEvent.VK_R);
            robot.keyPress(KeyEvent.VK_A);
            robot.keyPress(KeyEvent.VK_N);
          // robot.keyPress(KeyEvent.VK_F1);
          
        
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}


If you run this code and open a notepad or wordpad or any other  then this code will write "hi kiran" in the notepad.

No comments:

Post a Comment