Friday, July 13, 2012

0

Capture screen shot using java

  • Friday, July 13, 2012
  • vinod
  • Share

  • The java program is to capture screen image.If you press the Prt Scr(print screen)button on your keyboard you can take a snap same method is applied here.Java program takes the (.jpg) file.After running the program the input dialog box will appear for input the file name which has to be captured you have to input the file name.Then message dialog box will appear with message Screen captured successfully .Here we have to import 6 packages to do this program.
    • If you are not a java programmer you should follow this steps
    • Download java application click here to download
    • After downloading install the application and go to run and type cmd
    • Then type the selection path (example c:\cd\java\jdk\bin) then type edit
    • Now you can type the below coding
    • After typing the coding you have to save it. The file name and the class name should be same(case sensitive)
    • After saving go to file and select exit
    • Then you have to type javac filename.java for compile the program
    • Then the coding should not have any errors.After compiling run the program for running the program type java file name





    • createScreenCapture () is the method of the Robot class.This method is used to create an image
    • getScreenSize () method of the Toolkit class
    • getScreenSize () method of the Toolkit class


    Source code:


    [import javax.swing.*;
    import javax.imageio.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;

    public class Screensht
    {
    public static void main(String[] args) throws Exception
    {
    Screenshot ss = new Screensht();
    }

    public Screensht()
    {
    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 : ",
    "Get Input File", 1);
    if (!fileName.toLowerCase().endsWith(".gif")){
    JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".", "Dialog", 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.", "Success Message", 1);
    }
    }
    catch(Exception e){}
    }
    }
    }]


    Post a Comment

    Followers

    Subscribe