rkcole.com
Beginning with JDK 1.3, the java.awt.Robot class has made it possible to gain access to an image of the desktop throught its Robot.createScreenCapture() method.
The example below takes a snapshot of the screen and stores it in snapshot.jpg in the current directory. For a bit of added utility, there is an optional command-line parameter that causes the program to delay for a specified number of seconds prior to taking the snapshot. The delay would give you time to bring a window to the front or iconize your java command-window.
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;/**
* Save an image of the desktop to a "screenshot.jpg".
*
* Usage: java ScreenShot [seconds]
* seconds - optional number of seconds to wait prior to taking
* the screen picture.
*/
public class ScreenShot
{
public static void main(String[] argv) throws Exception
{
if(argv.length > 0)
{
try {
long time = Long.parseLong(argv[0]) * 1000L;
System.out.println("ScreenShot in " + argv[0] +" second(s)...");
Thread.sleep(time);
System.out.println("Snap!");
} catch(NumberFormatException nfe)
{
System.err.println(argv[0]+" is not a valid number of seconds.");
System.exit(-1);
}
}
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(size););
ImageIO.write(img, "JPG", new File("screenShot.jpg"));
}
}