Capturing screen shot

In this section, you will learn how to capture the
screen. Whatever you want to do by pressing the "Print Screen" button
on the keyboard, same thing is applied by the given program.
This program shows you how several methods and APIs are
used for capturing screen shot. This program capture the screen and makes the
"jpg" file. It show a frame which holds a command button labeled by
"Capture Screen Shot". When you click on the button then a input
dialog box will be opened for inputting the file name which has to be created
after capturing the screen. And then a message dialog box is opened with message
"Screen captured successfully.". For this purpose following methods
and APIs have been used:
createScreenCapture():
This is the method of the Robot class. This method is used to create an
image read by the screen. It takes the area which has been created using the
getDefaultToolkit().getScreenSize() method of the Toolkit class.
write():
This is the method of ImageIO class. This method is used to make image
file for the captured image. Before creating new image file the captured image
is stored in the created image buffer. This method takes three arguments as
follows:
- First is the rendered image.
- Second is the file format.
- And last is the output file name.
ImageIO:
This is the class of javax.imageio.*;
package. This class is used for reading an image or writing an image.
Here is the code of the program:
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class Screenshot {
public static void main(String[] args) throws Exception {
Screenshot ss = new Screenshot();
}
public Screenshot(){
JFrame frame = new JFrame("Screen Shot Frame.");
JButton button = new JButton("Capture Screen Shot");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent ae){
try{
String fileName = JOptionPane.showInputDialog(null, "Enter file name : ",
"Roseindia.net", 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with
\".gif\".", "Roseindia.net", 1);
}
else{
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
"Roseindia.net", 1);
}
}
catch(Exception e){}
}
}
}
|
Screen shot for the result of the above program:


Download this example.

|