Take a look to these two optional packages:
- Java Adavanced Imaging (http://java.sun.com/products/java-media/jai/index.html)
- Image I/O (http://developer.java.sun.com/developer/earlyAccess/imageio/)
The former comes with more image formats, but the latter is easier to use and, most important, is included in JDK 1.4.
Look at this example with ImageIO, it saves the content of a JFrame into a file:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class SaveSwing
{
public static void main(String[] args)
{
JFrame jframe = new JFrame("Hello there!");
jframe.setBounds(100, 100, 300, 200);
Container cp = jframe.getContentPane();
cp.add(new JLabel("Can you save me?"));
jframe.show();
BufferedImage image = new BufferedImage(cp.getWidth(), cp.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
cp.paint(image.getGraphics());
try { ImageIO.write(image, "png", new File("jframe.png")); }
catch(Throwable thr) { thr.printStackTrace(); }
System.exit(0);
}
}
I compiled your example but I get this error when I try to run it:
java.lang.IllegalArgumentException: raster == null!
at javax.imageio.IIOImage.<init>(IIOImage.java:94)
at javax.imageio.ImageWriter.write(ImageWriter.java:567)
at javax.imageio.ImageIO.write(ImageIO.java:1182)
at javax.imageio.ImageIO.write(ImageIO.java:1213)
at gimagez.SaveAWT.main(SaveAWT.java:3)
What am I doing wrong?