Tuesday, July 3, 2012

Screen Grabbing With Java's Robot Class

A few years back I started writing my own remote control software in Java. I had just begun learning the language when I undertook this lofty project. The Robot class is what gave me the idea in the first place. I thought it would be sooooooo cool to be able to grab a screenshot and send it across the network. This led to mouse controls, keyboard commands, etc. It was quite kewl. Anyway, I'm sure there are more elegant ways to accomplish this goal, but it all began with grabbing a screenshot. That's the subject of today's post.

To accomplish this, the screensize needs to be determined, the Robot class needs to be instantiated and a JLabel made available to display the image.

Dimension screensize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize()); JLabel my_screenshot = new JLabel();
Robot system;
try{
system = new Robot();
}
catch(AWTException a){
a.printStackTrace();}

The screen is grabbed with the Robot classs, but it is returned as a BufferedImage. Then place the image in the JLabel by creating a new ImageIcon and set it using using the JLabel's setIcon() method:

BufferedImage scr_shot = sys.createScreenCapture(new Rectangle(screensize));
my_screenshot.setIcon(new ImageIcon(scr_shot));

That's how to grab a basic screenshot using Java's Robot class.

No comments:

Post a Comment