Robot Class in Java

Today we are learning about Robot class in Java. Robot class is a package of Java AWT. Java AWT(Abstract Window Toolkit) is a java functional class that provides a GUI(Graphical user interface) for a java program.

Robot class is used to build an environment so we can take system input events to test automation or to build other application which requires control over the mouse and keyboard. In JDK 1.3 Robot class is introduced as a feature to take control over the mouse and keyboard.

The library required to import the Robot class in our program is given below:

import java.awt.Robot;

The robot class object is required to invoke its methods. So, let’s instantiate the Robot class.

Robot robot = new Robot();

Now discuss some methods of the robot class.

robot.mousePress(int buttons)// To press mouse buttons 
robot.mouseRelease(int buttons)// to release mouse key/button which was pressed earlier if we don't call 
//release method then the key will remain pressed until we terminate the program or we call the release method. 
robot.mouseMove(int x, int y)// to move the mouse cursor on the screen according to the x and y coordinates. 
robot.mouseWheel(int wheelAmt)// To scroll the mouse wheel according to the given amount.
robot.keyPress(int keycode) // To press a specific key of keyboard
robot.keyRelease(int keycode)// To release a specific key of the keyboard
robot.createScreenCapture(Rectangle screenRect) // Captures a screenshot in a rectangle shape
robot.getPixelColor(int x, int y)// It returns the color of a pixel at a specific
robot.setAutoDelay(int ms)// it sets the delay for the given amount of milliseconds.

 

Advantages of Robot Class :

  • Provides control over the Mouse and keyboard events.
  • Using Robot class we can interact with Operating system pop-ups which are not possible with Selenium web driver API.
  • The Robot class code or programs are easy to consume in the java Selenium scripts as the robot class is part of the Java package.

Limitations of Robot Class :

  • The methods mentioned above to control Keyboard and Mouse have some limitations.
  • Most of the methods like mouse move are dependent on the screen resolution.
  • Using Robot class methods or function switching between screens or windows is difficult.

Thank you for reading this blog.

Leave a Reply

Your email address will not be published.