3

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?

Simon
  • 9,255
  • 4
  • 37
  • 54
  • Please provide a small self-contained example that actually compiles. In your snippet, "offScreen" is used but not declared. – sleske Jun 09 '10 at 11:22

1 Answers1

1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820