help with saving a JPanel to jpg

I

info

I have a JPanel that I paint with a graph. The upper 40% is a graph
with a grid background, and the rest is a legend for the graph. When I
try to save the JPanel as a jpg, I get an image with the same
dimensions but there is no graph or legend and the grid, which uses the
dimensions to set the upper grid limit, covers the entire panel.
Everything on screen is fine. The current code is below. I've tried
the available varieties of paint and tried using the Robot class
(though this could be explored more). Any tips on where I'm messing up
or what could be changed to get this working would be appreciated.

java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
panel.getPreferredSize().width,
panel.getPreferredSize().height,
java.awt.image.BufferedImage.TYPE_INT_RGB);
java.awt.Graphics2D g = image.createGraphics();
g.setRenderingHint(java.awt.RenderingHints.KEY_FRACTIONALMETRICS,
java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
panel.paintAll(g);
g.dispose();
javax.imageio.ImageIO.write(image, "jpeg",
new java.io.File("./" + jtf.getText() + ".jpg"));
image.flush();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top