1

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, since 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?

zergylord
  • 4,368
  • 5
  • 38
  • 60

2 Answers2

2

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.

mdma
  • 56,943
  • 12
  • 94
  • 128
  • I'm a little confused as to how I'd denote that the 'applet' variable refers to the specific instance of the applet that I'm running. I've tried running something similar to your code after starting up the applet viewer, but it keeps telling me that 'size' == java.awt.Dimension[width=0,height=0], which I take to mean that 'applet' isn't refering to the instance of the applet thats running :-( – zergylord Aug 25 '11 at 23:24
  • are you sure you're grabbing the reference after the viewer has been initialized? If instead, you're instantiating a new applet, then it will have zero size. If your applet doesn't rely upon AppletContext then you can simply instantiate it, and put it in a Frame and call init() and start(). i.e. create your own viewer. – mdma Aug 25 '11 at 23:40
  • It does unfortunately rely on AppletContext, so I imagine I'm stuck using the standard Appletviewer. I think I might be grabbing the applet reference wrong, as I do this (for Applet class Foo) right after opening the applet in the appletviewer: applet = Foo(). Is this incorrect? – zergylord Aug 25 '11 at 23:48
0

+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.

Prasith Govin
  • 1,267
  • 12
  • 8