Component has a method paint(Graphics). That method will paint itself on the passed graphics. This is what we are going to use to create the BufferedImage, because BufferedImage has the handy method getGraphics(). That returns a Graphics-object which you can use to draw on the BufferedImage.
UPDATE: But we have to pre-configure the graphics for the paint method. That's what I found about the AWT Component rendering at java.sun.com:
When AWT invokes this method, the
Graphics object parameter is
pre-configured with the appropriate
state for drawing on this particular
component:
- The Graphics object's color is set to the component's foreground property.
- The Graphics object's font is set to the component's font property.
- The Graphics object's translation is set such that the coordinate (0,0) represents the upper left corner of the component.
- The Graphics object's clip rectangle is set to the area of the component that is in need of repainting.
So, this is our resulting method:
public static BufferedImage componentToImage(Component component, Rectangle region) throws IOException
{
BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = img.getGraphics();
g.setColor(component.getForeground());
g.setFont(component.getFont());
component.paintAll(g);
if (region == null)
{
region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
}
return img.getSubimage(region.x, region.y, region.width, region.height);
}