【问题标题】:How to take a screenshot of a JPanel with robot?如何使用机器人截取 JPanel 的屏幕截图?
【发布时间】:2014-08-21 17:41:01
【问题描述】:

这就是我如何制作整个 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,这是我真正想要的。

【问题讨论】:

  • 标为重复的 Q&A 从标题上看可能看起来不正确,但答案还包括获取显示组件的图像。
  • @AndrewThompson 但不适用于 java.awt.Robot
  • 但要使用Robot,则需要getLocationOnScreen() 用于感兴趣的组件。
  • @AndrewThompson 我个人不会关闭这个。他明确要求提供机器人截图。当然,应该提到存在绘制成 BufferedImage 的可能性,但也许他只是在寻找一种方法来确定面板的 on-screen 边界......? [编辑:我对这个评论太慢了,但还是把它留在这里]
  • 我同意@AndrewThompson 关于几何的分析,但另请参阅Zoom

标签: java image swing screenshot jcomponent


【解决方案1】:

这可能会有所帮助:

/**
 * 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多