3

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?

Jason
  • 11,263
  • 21
  • 87
  • 181

2 Answers2

6

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,…);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
3

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.

Nate
  • 16,748
  • 5
  • 45
  • 59
  • 1
    The only downside with the Robot is I have no way of knowing what the screen coordinates of the graph will be, since it rarely opens up in the same space twice. But the ImageIO seems perfect for my needs – Jason Jan 26 '10 at 16:01
  • 3
    You can calculate the screen coordinates of any component by using `SwingUtilities.convertPointToScreen(Point)`. – Nate Jan 26 '10 at 17:16