Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output a jFrame to jpeg or bitmap

Tags:

java

graphics

I've been working on an assignment, and have all the requirements completed. The project is to compare the differences in runtime between a linear search algorithm and a binary search. I have a graph class that puts out the results of those searches in a xy graph.

The graph object is a Turtle class that extends JFrame. Is there any way I can convert that graph object to a bitmap and save it for future printing?

The professor requires printouts of the results. Since I don't want a printout of every time the program is run, I would prefer to save the graphics results in a designated folder, rather than using screen-grab.

Unfortunately, I haven't come up with any answers on Google or here. Is something like this even possible?

like image 613
Jason Avatar asked Jan 18 '26 06:01

Jason


2 Answers

Another approach is to tell your Component to paint() itself into a BufferedImage, as seen in this complete example. The Container returned by a JFrame's getContentPane() method is suitable. In summary:

Component component = f.getContentPane();
BufferedImage image = new BufferedImage(…);
component.paint(image.getGraphics());
ImageIO.write(image,…);
like image 138
trashgod Avatar answered Jan 20 '26 19:01

trashgod


You can pass the bounds of the area into the Robot.createScreenCapture(Rectangle) method to create a BufferedImage of the area. The easiest way to save the screenshot as an image file is to use the ImageIO class.

like image 27
Nate Avatar answered Jan 20 '26 19:01

Nate