How to make a screenshot ?

Making a screenshot in Java is quite simple thanks to java.awt package with a lot of graphical tools. First, take a look at the sample code:

public class ScreenshotTest {

	public void test() {
		final Rectangle screenRect=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
			// 5 seconds to found the thing to capture
			final BufferedImage capture=new Robot().createScreenCapture(screenRect);
			File screenshot = new File("/home/bartosz/tmp/screenshot_"+System.nanoTime()+".jpg");
			ImageIO.write(capture, "bmp", screenshot);
			assertTrue("Screenshot's file doesn't exist", screenshot.isFile());
		catch(final Exception e){
			fail("An exception occured: "+e.getMessage());


The code is using Rectangle object that constructs an area containing our screenshot. The size of this area is equal to screen size. Another object, the instance of Robot class, is used to control some of system events. For example, you can use it to provoke key press (keyPress method) or mouse click (mousePress method). But we use it to create an image of pixels read from the screen. A createScreenCapture() helps us to achieve that. After, we save generated image to a file and check if it was correctly saved.