Java屏幕截圖工具 捕獲屏幕
import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage;import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants;
/**
捕獲屏幕,屏幕截圖工具 */ public class ScreenCaptureFrame extends JFrame implements ActionListener {
private ScreenCaptureUtil scrCaptureUtil = null;// 捕獲屏幕的工具類 private PaintCanvas canvas = null;// 畫布,用于畫捕獲到的屏幕圖像
public ScreenCaptureFrame() {
super("Screen Capture"); init();
}
/**
初始化 */ private 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 ScreenCaptureFrame(); } }
/**
抓屏工具類 */ class ScreenCaptureUtil { private Robot robot = null;// 抓屏的主要工具類 private Rectangle scrRect = null;// 屏幕的矩形圖像
public ScreenCaptureUtil() {
try { robot = new Robot();// 創建一個抓屏工具 } catch (Exception ex) { System.out.println(ex.toString()); } // 獲取屏幕的矩形圖像 Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize(); scrRect = new Rectangle(0, 0, scrSize.width, scrSize.height);
}
/**
- 抓屏方法
- @return 返回一個圖像
*/
public BufferedImage captureScreen() {
BufferedImage scrImg = null;
try {
} catch (Exception e) {scrImg = robot.createScreenCapture(scrRect);// 抓的是全屏圖
} return scrImg; } }System.out.println(e.toString());
/**
畫布類,用于顯示抓屏得到的圖像 */ class PaintCanvas extends JPanel { private ScreenCaptureUtil scrCaptureUtil = null;// 抓屏工具 private BufferedImage scrImg = null;// 待畫的圖像
public PaintCanvas(ScreenCaptureUtil screenUtil) {
this.scrCaptureUtil = screenUtil;
}
/**
重載JPanel的paintComponent,用于畫背景 */ 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) {
} g.dispose();// 釋放資源 }this.paintComponent(g);// 畫圖
}</pre>