java实现屏幕捕捉程序

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变成兵书》
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值