Your Computer Science Resource

HOW-TO: Screen Capture Using Java’s Robot Class

At some point or another, you may come across a time when you need to capture the user’s screen and save it as an image. Maybe you’re making your own “print screen” program, or doing some other image analysis. Regardless, there is a really simple way to capture the user’s screen, and here it is.

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ScreenCapture {

	public static void main( String[] args ) {

		/**
		 * Ideally, this should be set to the dimensions of
		 * the user's screen
		 */

		Rectangle rect = new Rectangle();
		rect.width = 1680;
		rect.height = 1050;
		BufferedImage bi;

		/**
		 * Grab the screen and put it in a JFrame.
		 */

		try {

			JFrame frame = new JFrame();		// Frame to show the image
			Robot robot = new Robot();		// Create the robot
			bi = robot.createScreenCapture(rect);	// This is where the magic happens

			/**
			 * Here we just add the buffered image to a
			 * JLabel using ImageIcon. Then we pack the
			 * JFrame and set it to visible.
			 */

			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.add(new JLabel(new ImageIcon(bi)));
			frame.pack();
			frame.setVisible(true);

		} catch ( AWTException e ) {

			e.printStackTrace();

		} // end try block

	} // end main method

} // end class ScreenCapture

If you don’t want to capture the screen immediately, you can set the robot on a delay right before you call the createScreenCapture method, such as:

Robot robot = new Robot();		// Create the robot
robot.delay(5000);			// Delay in Milliseconds
bi = robot.createScreenCapture(rect);	// This is where the magic happens

You can (and probably should) change the dimensions of where the screenshot takes place by changing lines 20 and 21:

rect.width = 800;	// Change to your preferred width
rect.height = 600;	// Change to your preferred height

If you want to use the user’s screen size as the dimensions for the screenshot, change this to the following:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle();
rect.width = dim.width;
rect.height = dim.height;

Enjoy!

Tags: , , ,

2 Responses to “HOW-TO: Screen Capture Using Java’s Robot Class”

  1. Computer Cranium - Your Computer Science Resource » Blog Archive » HOWTO: Save a BufferedImage to Disk

    [...] I showed you how to take a screenshot and display it in a JFrame using Java’s Robot class. What if you wanted to save the image to [...]

  2. Computer Cranium - Your Computer Science Resource » Blog Archive » PROJECT: Screen Capture Utility

    [...] my previous posts on how to take a screenshot and how to save an image to disk, I’ve created a Screen Capture Utility extending these basic [...]

Leave a Reply