In Java, Robot is a class that belongs to the java.awt package. It also extends the Object class. The class is used to generate native system input events for test automation, self-running demos, and other applications where the control of the mouse and keyboard is required. In other words, we use the Java Robot class to trigger the input events, such as mouse click, keypress, etc. In this section, we will discuss the Java Robot class and its methods. Along with this, we will also create a Java program to control the keyboard and mouse. By using the Robot class we will create a Java program and control the keyboard and mouse.
The primary purpose of the Robot class is to facilitate automated testing of Java platform implementations. In short, the Robot class is used to control the peripherals (mouse and keyboard). It facilitates the three main functionalities, provides control over the mouse and keyboard, and captures the screen also.
Java Robot Class Methods
The Robot class extends the Object class so the methods of the Object class also inherited in the Robot class. All the above methods throw IllegalArgumentException if the key or mouse click is not correctly specified.
When we run the above program, the notepad.exe automatically opens and starts hitting the corresponding keys as arranged in order. After pressing each key there is an interval of 500 milliseconds (ms), you can increase or decrease the delay accordingly. Hence, the string welcome to javatpoint is simulated types on the notepad.
Robot Class Mouse Events
Let's understand how to simulate mouse events using the Java Robot class.
The method parses one or more mouse buttons. After pressing the muse button should be released by invoking the mouseRelease(int buttons) method. For mouse events, there are following button masks (that passed in the parameter) are available:
The above values returned by the InputEvent.getMaskForButton(button) method. The method also accepts the following standard button masks:
It releases the mouse button that is previously clicked. It accepts the same parameter as the method mousePress() method accepts. Suppose, we want to release the right-click then will invoke the robot.mouseRelease(InputEvent BUTTON3_DOWN_MASK) method.
mouseMove(int x, int y)
The method is used to move the mouse pointer to the specified screen position. It parses two parameters x and y that are coordinates. For example, mouseMove(300, 100).
The method rotates the mouse wheel. It parses a parameter wheelAmt that is a number of notches to move the wheel. The parameter may have a positive or negative value. The positive value moves the wheel in the down direction (towards the user) and the negative value moves the wheel in the up direction (away from the user).
Let's implement the mouse simulation in a Java program using the Java Robot class.
To move the pointer, click on the OK button, as we click on the OK button the pointer starts moving to the specified coordinate.