Question:
In my application, I want to convert the content of a component into a GIF image. I know how to convert an Image object to a GIF, but I don’t know how to convert the contents of a frame into an Image object. Could you help me?
Answer:
Capturing the graphical contents of a container in an Image
is done much as how you would print the contents, except instead of printing to a PrintGraphics
object, you print to the Graphics
object of the Image
. The printComponents
method does all the work for you. The following program creates two frames, one containing a button and a label, and the other simply a blue background. When you press the button in the first frame, the program creates an offscreen image, prints the first frame to image, hides the frame, and paintsthe image to the second frame.
import java.awt.*;import java.awt.event.*;public class FrameToImage { static class ImageFrame extends Frame { private Image __image = null; public void paint(Graphics g) { if(__image == null) super.paint(g); else g.drawImage(__image, 0, 0, this); } public void setImage(Image image) { __image = image; } } public static final void main(String[] args) { final Frame frame1; final ImageFrame frame2; final Button button; WindowListener exitListener; frame1 = new Frame(); frame1.setSize(200, 200); frame1.setResizable(false); frame2 = new ImageFrame(); frame2.setSize(200, 200); frame2.setResizable(false); exitListener = new WindowAdapter() { public void windowClosing(WindowEvent e) { Window window = e.getWindow(); window.setVisible(false); window.dispose(); System.exit(0); } }; frame2.addWindowListener(exitListener); button = new Button("Convert to Image"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Image image; Dimension size; size = frame1.getSize(); image = frame1.createImage(size.width, size.height); frame1.setVisible(false); frame1.printComponents(image.getGraphics()); frame2.setImage(image); frame2.repaint(); } }); frame1.add(new Label("Frame 1", Label.CENTER), BorderLayout.CENTER); frame1.add(button, BorderLayout.NORTH); frame1.setLocation(10, 10); frame2.setBackground(Color.blue); frame2.setLocation(300, 10); frame1.setVisible(true); frame2.setVisible(true); }}