|
|
主要实现代码如下所示 : public class MainClass extends JFrame implements ActionListener {
/** * @param args */ private ScreenCapture scrCapture = null;
private PaintCanvas canvas = null;
public MainClass() { super("Screen Capture"); init(); } public void actionPerformed(ActionEvent e) { canvas.drawScreen(); }
private void init() { scrCapture = new ScreenCapture(); canvas = new PaintCanvas(scrCapture); 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 static void main(String[] args) { // TODO Auto-generated method stub System.out.println("System started"); new MainClass(); System.out.println("window is visible"); }
}
class ScreenCapture {
/** * @param args */ private Robot robot = null;
private Rectangle scrRect = null;
public ScreenCapture() { 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); }
public BufferedImage captureScreen() { BufferedImage bufImg = null;
try { bufImg = robot.createScreenCapture(scrRect); } catch (Exception e) { System.out.println(e.toString()); } return bufImg; } }
class PaintCanvas extends JPanel { private ScreenCapture screen = null;
private BufferedImage scrImg = null;
public PaintCanvas(ScreenCapture screen) { this.screen = screen; }
protected void paintComponent(Graphics g) { // TODO Auto-generated method stub // BufferedImage scrImg = screen.captureScreen(); 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 = screen.captureScreen(); if (scrImg != null) { this.paintComponent(g); } g.dispose(); }
}
|
|