Java GUI components can be dumped to standard image file using code
exampled below. However, the outermost frame, including title header,
of Frame or JFrame can't be captured through this method because they
aren't rendered by Java but the native windowing system. I'd like to
know a workaround, if any.
<code>
public static void writeComponentToFile
(Component comp, String fileName){
//output file
String[] temp = fileName.split("\\.");
String ext = temp[temp.length - 1];
BufferedImage bImage
= new BufferedImage(comp.getWidth(), comp.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bImage.getGraphics();
comp.paint(g);
try{
File file = new File(fileName);
if (ext.equals("png")){
ImageIO.write(rImage, "png", file);
}
else if (ext.equals("jpg")){
ImageIO.write(rImage, "jpg", file);
}
else{
System.err.println("Unsupported format: " + ext);
System.err.println("We only support .jpg and .png files);
}
}
catch(Exception e){
e.printStackTrace();
}
}
</code
Harald Hein - 08 Dec 2003 10:03 GMT
> Java GUI components can be dumped to standard image file using code
> exampled below. However, the outermost frame, including title header,
> of Frame or JFrame can't be captured through this method because they
> aren't rendered by Java but the native windowing system. I'd like to
> know a workaround, if any.
Maybe java.awt.Robot
hiwa - 09 Dec 2003 01:50 GMT
> > Java GUI components can be dumped to standard image file using code
> > exampled below. However, the outermost frame, including title header,
[quoted text clipped - 3 lines]
>
> Maybe java.awt.Robot
Thanks Harald. It works fine. But couple of caveats here:
<code>
RenderedImage getCompImageFromRobot(Component comp){
int x, y, width, height;
BufferedImage bImage = null;
//these conditionals are necessary, but I don't know why
if (comp instanceof Window){
x = comp.getX();
y = comp.getY();
}
else{
Point p = comp.getLocationOnScreen();
x = p.x;
y = p.y;
}
width = comp.getWidth();
height = comp.getHeight();
Rectangle rec = new Rectangle(x, y, width, height);
try{
Robot robo = new Robot();
//you need to give generous amount of delay
robo.delay(100);
bImage = robo.createScreenCapture(rec);
}
catch(Exception e){
e.printStackTrace();
}
return bImage;
}
</code