Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

wrldwzrd89

macrumors G5
Original poster
Jun 6, 2003
12,110
77
Solon, OH
Is there a way, in Java, to take a given Container, and have it recursively draw the whole layout (including sub-containers, and THEIR sub-containers, etc.) to a BufferedImage object? Among other things, being able to do this would make supporting printing a LOT easier, even if the printing has to be done in an external program, by way of exporting the BufferedImage object to a PNG file then opening it in an image viewer.

If an example of what I'm trying to export would help at all, I offer the Mazer5D 3.0.0 beta builds' Object Help (which is dynamically generated) as a good example, here. The executable is there, for Mac OS X, Windows, and other platforms, along with the source code.
 
If I understand your question correctly, something like:
Code:
  yourContainer.paint( yourBufferedImage.createGraphics() );
You might have to futz with the Container's size & location first. Or maybe use a transform on the Graphics2D.
 
This is giving me a black image, for some reason... it writes the image okay, but nothing gets displayed when I open it in an image editor.

Here is the code I'm using, with comments added:
Code:
// Temp code to export help
Container c = this.hv.getHelp(); // Some Container object we're given
Dimension d = c.getPreferredSize();
BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
c.paintAll(bi.createGraphics());
try {
	ImageIO.write(bi, "PNG", new File("objecthelp.png"));
	Messager.showTitledDialog("Exporting help was successful", "Help");
} catch (IOException io) {
	Messager.showErrorDialog("Error exporting help!", "Error");
}
// End temp code
 
Success! I finally got this to work properly, by calling paintComponents() instead of paint(), and changing the color of the BufferedImage object to the same as the background color of the help, with a nested for loop. :D
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.