
How to take screenshot in Java
This is a very interesting program where you will be able to take screenshots
of you computer through a simple progam shown below.
Program 1:A short and simple version for testing....
package codermag.net;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
public class ScreenshotGrabber {
public static void main(String[] args) throws IOException,
HeadlessException, AWTException {
ImageIO.write(new Robot().createScreenCapture(new Rectangle(Toolkit
.getDefaultToolkit().getScreenSize())), "jpg", new File(
"D:/screenshot.jpg"));
}
}
Output:

Program 2:Coding standards followed with proper error handling
package codermag.net;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenshotGrabber {
public static void main(String[] args) {
try{
Robot robot=new Robot();
Rectangle rectangle=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage=robot.createScreenCapture(rectangle);
ImageIO.write(bufferedImage, "jpg", new File("D:/screenshot.jpg"));
}
catch (IOException e) {
e.printStackTrace();
} catch (AWTException e) {
e.printStackTrace();
}
}
}
Capture screen with variable/dynamic screen size
If you need to change the screen dimensions according to your wish than take a look at thefollowing code snippet. The method takes in the height and width of the screenshot to be taken.
Please note that the height and width cannot be 0, so proper exception handling must be implemented.
public void captureScreen(int height, int width) {
Rectangle rectangle = new Rectangle();
rectangle.setSize(height, width);
try
{
ImageIO.write(new Robot().createScreenCapture(rectangle), "jpg",
new File("D:/screenshot.jpg"));
}
catch (IOException e) {}
catch (AWTException e) {}
}