java实现屏幕捕捉程序

来源:互联网 发布:宝塔 递推 算法 编辑:程序博客网 时间:2024/05/19 12:36
package packclass1;import java.awt.*;import java.awt.event.*;import java.awt.image.*;import javax.swing.JFrame;import javax.swing.JButton;import javax.swing.JPanel;import javax.swing.WindowConstants;public class ScreenCapture extends JFrame implements ActionListener {private ScreenCaptureUtil scrCaptureUtil = null;private PaintCanvas canvas = null;public Class1(){super("Screen Capture");init();}public void init(){scrCaptureUtil = new ScreenCaptureUtil();canvas = new PaintCanvas(scrCaptureUtil);Container c = this.getContentPane();c.setLayout(new BorderLayout());c.add(canvas,BorderLayout.CENTER);JButton capButton = new JButton("抓屏");c.add(capButton,BorderLayout.SOUTH);capButton.addActionListener(this);this.setSize(400, 400);this.setVisible(true);this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}public void actionPerformed(ActionEvent e){canvas.drawScreen();}public static void main(String[] args){new ScreenCapture();}}class ScreenCaptureUtil{private Robot robot = null;private Rectangle scrRect =null;public ScreenCaptureUtil(){try{robot = new Robot();}catch(Exception e){System.out.println(e.toString());}Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();scrRect = new Rectangle(0,0,scrSize.width,scrSize.height);}public BufferedImage captureScreen(){BufferedImage scrImg = null;try{scrImg = robot.createScreenCapture(scrRect);}catch(Exception e){System.out.println(e.toString());}return scrImg;}}class PaintCanvas extends JPanel{private ScreenCaptureUtil scrCaptureUtil = null;private BufferedImage scrImg = null;public PaintCanvas(ScreenCaptureUtil scrCaptureUtil){this.scrCaptureUtil = scrCaptureUtil;6}protected void paintComponent(Graphics g){if(scrImg !=null){int iWidth = this.getWidth();int iHeight = this.getHeight();g.drawImage(scrImg, 0, 0, iWidth, iHeight, 0,0,scrImg.getWidth(),scrImg.getHeight(),null);}}public void drawScreen(){Graphics g = this.getGraphics();scrImg=scrCaptureUtil.captureScreen();if(scrImg != null){this.paintComponent(g);}g.dispose();}}
本程序来自桂颖,任显衡的《java变成兵书》
0 0
原创粉丝点击