Sunday, March 27, 2016

Entire-Screen Capture

This program captures the entire screen and saves it as an image file. The process is done through the use of the Robot class. The setState(JFrame.ICONIFIED) method minimizes the frame before the process begins and the setState(JFrame.NORMAL) method restores the frame when the process ends.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;

public class ScreenCapture2 extends JFrame{
    private JButton bcapture=null;
    
    public ScreenCapture2(){
        super("SCreen Capture");
        setSize(200,100);
        
        bcapture=new JButton("Capture");
        bcapture.addActionListener(new ButtonHandler());
        bcapture.setMnemonic(KeyEvent.VK_G);
        
        setLayout(new FlowLayout());
        add(bcapture);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        show();
    }
    
    class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            if(e.getActionCommand()=="Capture"){
                capturing();
            }
        }
    }
    
    void capturing(){
                try{
                    this.setState(JFrame.ICONIFIED);
                    Robot robot=new Robot();
                    String fileName="screenshot.jpg";
                    Rectangle rect=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                    BufferedImage bufImage=robot.createScreenCapture(rect);
                    ImageIO.write(bufImage, "jpg", new File(fileName));                                
                    this.setState(JFrame.NORMAL);
                }catch(Exception ex){
                    
                }                    
    }
 
    public static void main(String[] args) {
        ScreenCapture2 ap=new ScreenCapture2();
    }
}

No comments:

Post a Comment