Paint java GUI component to image file

Posted by Simon on Stack Overflow See other posts from Stack Overflow or by Simon
Published on 2010-06-09T11:15:37Z Indexed on 2010/06/09 11:52 UTC
Read the original article Hit count: 361

Let's say I have

JButton test = new JButton("Test Button");

and I want to draw the button into an image object and save it to a file.

I tried this:

BufferedImage b = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
test.paint(b.createGraphics());

File output = new File("C:\\screenie.png");

try
{
    ImageIO.write(b, "png", output);
}
catch (IOException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

This code produced an empty 500x500 PNG-file. Does anyone know how I can draw the GUI component to an image file?

© Stack Overflow or respective owner

Related posts about java

Related posts about painting