如何用机器人拍摄JPanel的截图?

时间:2014-07-01 08:22:30

标签: java image swing screenshot jcomponent

这就是我如何制作整个JFrame的截图

Rectangle screenRect = cap.getBounds();
File docfile = new File("image");
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "png", file);

cap是JFrame。但是当我为cap使用JPanel时,我得到了我的桌面的部分截图,不仅仅是JPanel,我真正想要的。

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助:

/**
 * Perform a screen capture of a JPanel to a Buffered Image
 * 
 * @param panel - Panel to screen copy
 * @return BufferedImage
 * 
 * @throws AWTException - if the platform configuration does not allow low-level
 *                      input control. This exception is always thrown when
 *                      GraphicsEnvironment.isHeadless() returns true
 */
public static BufferedImage printScreen(JPanel panel) throws AWTException {     
    Point p = panel.getLocationOnScreen();
    Dimension dim = panel.getSize();
    Rectangle rect = new Rectangle(p, dim);

    Robot robot = new Robot();  
    return robot.createScreenCapture(rect);
}