Simon
Simon

Reputation: 9365

Paint java GUI component to image file

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?

Upvotes: 3

Views: 1950

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

The image is not empty, it contains a button of the size 0x0 at 0,0.

Solution: You must add a layout or set the size of the button manually.

Note: To test it, render the component(s) on a JFrame, first. That allows you to quickly see what will happen.

Upvotes: 1

Related Questions