Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
Simon Avatar asked Nov 30 '25 04:11

Simon


1 Answers

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.

like image 148
Aaron Digulla Avatar answered Dec 02 '25 16:12

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!