How can I capture a specific component in my Java application as opposed to my full primary monitor?
Current code example of how I collect the image:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage image = null;
try {//take the screenshot and store in buf img
image = new Robot().createScreenCapture(screenRect);
} catch (AWTException e2) {
e2.printStackTrace();
}
Example of components I want to screen shot would be JFrame, Applet, and JPanels. An example with any of those would be satisfactory in answering this question.
EDIT: This code solves the issue of allowing you to run and take screenshots while minimized or in background. Thanks to Dando18.
public static BufferedImage createImage(JComponent comp) {
int w = comp.getWidth();
int h = comp.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
comp.paint(g);
return bi;
}
Remaining issues:
- When I take a screenshot by using getComponent or getContentPane on my JFrame and pass it over to the createImage function it shows every control/component and their content is shown on the Main JFrame but the applet will not appear even though it is showing me my game it is sending back black screen shots of that portion.
How it is loaded in my application:
The following conditions are for my applet.
- Applet is on Main JFrame
- Stub of Applet implements AppletContext, AppletStub
Main JFrame -> Calls class named Loader and passes parameters to it -> Parameters are passed to my class called Stub from Loader -> Applet is set to the Stub -> Applet is added to Main JFrame centered.
I don't understand why this Component cannot be captured along with the others on the Main JFrame. I know the Applet is a Component of awt not JComponent of swing and I have tried just a screenshot of Applet by returning it from the Loader class and passing just Component to createImage overriding the signature, it seemed to only capture a small window which was different than capturing the Main JFrame of my application but nonetheless it was a black image.
Robot?ComponentImageCapturein this answer. 2) Tip: Add @Dando18 (or whoever, the@is important) to notify the person of a new comment.