1

I created a JFrame that loads an external applet for a game like so:

//Setup everything for the Stub.. Below adds the stub to the applet and creates it.
DownloadFile(new URL(World + "/" + Archive), "./gamepack.jar");
CAppletStub Stub = new CAppletStub(new URL(World), new URL(World), this.Parameters);
applet = (Applet) new URLClassLoader(new URL[] {new URL(World.toString() + "/" + Archive)}).loadClass("Rs2Applet").newInstance();

applet.setStub(Stub);
applet.init();
applet.start();
applet.setPreferredSize(new Dimension(Width, Height));
Frame.getContentPane().add(applet);

I'm trying to screenshot this applet or get it to draw its surface in a BufferedImage. I tried subclassing "Applet" and casting my URLClassLoader to that class but it can't cast which makes sense.

How can I capture everything the applet is rendering into an Image?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Brandon
  • 22,723
  • 11
  • 93
  • 186

2 Answers2

2

This works for any Component, not only Applets:

public static BufferedImage toBufferedImage(Component component) {
    BufferedImage image = new BufferedImage(component.getWidth(), 
        component.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    component.paint(g);
    return image;
}
Pino
  • 7,468
  • 6
  • 50
  • 69
  • You should dispose the `Graphics` object once you're done with drawing: `g.dispose()` – gcvt Apr 14 '13 at 18:50
  • This creates a Black Image when used with the Applet :S – Brandon Apr 14 '13 at 19:15
  • @gcvt: No, the Javadoc of Graphics.dispose() says "Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return". – Pino Apr 15 '13 at 08:11
  • @CantChooseUsernames: I've just tested it with an Applet and a JApplet runned by appletviewer: it works, check again or post your code. – Pino Apr 15 '13 at 08:13
1

I use Screen Image for normal Swing Applications. Don't know if loading an applet into a JFrame causes any problems.

camickr
  • 321,443
  • 19
  • 166
  • 288