Java’s Robot class makes it really easy to capture the screen as an image. Here, we’ll take a screenshot using the dimensions of the user’s screen resolution, show the image in a JFrame, and save it to disk as a GIF.
The Code
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SimpleScreenCapture {
/**
* @param args
*/
public static void main( String[] args ) throws Exception {
// Make a rectangle according to the size of the screen
Rectangle rectangle = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );
// Initialize a JFrame where we will show the image
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// Take the screenshot
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture( rectangle );
// Use a JLabel icon to display the image
frame.add( new JLabel( new ImageIcon( img ) ) );
frame.pack();
frame.setVisible( true );
// Save the image as a GIF to disk
File file = new File( "screenshot.gif" );
ImageIO.write( img, "gif", file );
}
}

2 Trackbacks
[...] 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 [...]
[...] 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 [...]