import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class ScreenShotTest {

	public static void main(String args[]) throws InterruptedException, InvocationTargetException {

        javax.swing.SwingUtilities.invokeAndWait(() -> {
            JFrame frame = new JFrame();
            frame.setSize(400, 400);
            frame.setVisible(true);
            
            try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            
            try {
				Robot robot = new Robot();
				Rectangle boundary = new Rectangle(frame.getLocationOnScreen(),
		                frame.getSize());
				BufferedImage bufferedImage = robot.createScreenCapture(boundary);
				File outputfile = new File("screenshot.jpg");
				ImageIO.write(bufferedImage, "jpg", outputfile);
			} catch (AWTException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
            System.out.println("Screen shot captured.");
        });
    }
}
