2

This is how I can make a screenshot of a whole JFrame

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

with cap being a JFrame. But when I use a JPanel for cap, I get a partly screenshot of my desktop, not only of the JPanel, what I actually want.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Saphire
  • 1,812
  • 1
  • 18
  • 34
  • The Q&A marked as duplicate might seem incorrect from the title, but the answer also covers gaining an image of a displayed component. – Andrew Thompson Jul 01 '14 at 08:25
  • @AndrewThompson but not with java.awt.Robot – Saphire Jul 01 '14 at 08:26
  • But for using the `Robot` it is necessary to `getLocationOnScreen()` for the component of interest. – Andrew Thompson Jul 01 '14 at 08:27
  • 1
    @AndrewThompson I personally would not have closed this. He explicitly asked for a screenshot with a robot. Of course, one should mention that the possibility of painting into a BufferedImage exists, but maybe he was just looking for a way to determine the **on-screen** bounds of a panel...? [EDIT: I was too slow with this comment, but leave it here nevertheless] – Marco13 Jul 01 '14 at 08:28
  • *"but not with `java.awt.Robot`"* True, not with `Robot` (the first comment) but if '*only* with `Robot`' then this hints of an [XY problem](http://meta.stackexchange.com/q/66377).. I'd tend to use 'whatever works best'. Using the paint methods of the component, we automatically get the right size and location, and it can be done even in a sand-boxed app. (until the app. goes to save the image to disk). – Andrew Thompson Jul 01 '14 at 08:31
  • @Marco13 Perhaps I *was* too hasty. I should have clarified the 'why `Robot`?' prior to closing. – Andrew Thompson Jul 01 '14 at 08:32
  • 1
    I agree with @AndrewThompson's analysis regarding geometry, but see also [`Zoom`](http://stackoverflow.com/a/3742841/230513). – trashgod Jul 01 '14 at 15:45

1 Answers1

0

It may help:

/**
 * 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);
}
Alex Byrth
  • 1,328
  • 18
  • 23