Getting a screenshot of a Java applet
I'm trying to use the Java Robot class to do some automated testing for various projects I've worked on and I'm having some trouble getting screen shots of any program that isn't full screen.
For full screen programs I just use:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); BufferedImage image = robot.createScreenCapture (dim);
I know that I can't get a screenshot of a particular window in general, si开发者_运维问答nce I'm pretty sure Java doesn't know where on the screen each window is (since its OS specific).
But I'm hoping I could still get a screeenshot of an applet in an applet-viewer, since the window is connected to the JVM in one way or another.
So, any ideas on whether or not this is possible? And if so, how I might go about doing it?
Assuming you have a reference to your applet (or any other Component), you create an off-screen Graphics2D instance and have the component paint itself to that.
Component applet = ...; // the applet
Dimension size = applet.getSize();
BufferedImage offScreenImage = (BufferedImage) applet.createImage(size.width, size.height);
Graphics2D g2 = offScreenImg.createGraphics();
g2.setBackground(applet.getBackground());
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, size.width, size.height);
applet.paint(g2);
// now you can use BufferedImage as before
The key is Component.createImage which creates an off-screen image for double buffering.
+1 on the above answer and you should use double buffering anyways as a general design pattern in java applets to prevent flickering and other issues with updating the view.
精彩评论