How It works
How to use java.awt.Robot
Opens notepad and enters text
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. If you run this code and open a notepad then this code will write hi budy in the notepad.
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();
// Creates the delay of 5 sec so that you can open notepad before
// Robot start writting
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);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
To capture Desktop
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage image = new Robot().createScreenCapture(new Rectangle(screenSize));
ImageIO.write(image, "png", new File(fileName));
Alternatively, we might capture our JFrame, including its window decoration, as follows
public void captureFrame(JFrame frame, String fileName) throws Exception {
BufferedImage image = new Robot().createScreenCapture(frame.getBounds());
ImageIO.write(image, "png", new File(fileName));
}