java robot 截屏_Java Robot类实现截屏

Java Robot类实现截屏

作者:    文章来源:

发布日期:2005年01月01日    浏览次数:1次

主要实现代码如下所示

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值