Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorating a JFreeChart

I would like to decorate all my generated JFreeCharts with a timestamp in the corner. Is there a way within the JFreeChart framework to draw on the image after the chart has been generated?

EDIT: Note that these charts are being generated in a background thread and distributed via a servlet, so there is no GUI and I can't just display the timestamp on a separate component.

like image 680
Robert J. Walker Avatar asked May 29 '26 08:05

Robert J. Walker


2 Answers

One approach would be to subclass ChartPanel and override the paint(Graphics) method to first chain to super.paint(Graphics) and subsequently render the additional text on top of the chart.

This feels a bit hacky to me though and I'd personally favour simply adding the ChartPanel to another container JPanel along with a JLabel representing the timestamp.

like image 181
Adamski Avatar answered May 31 '26 20:05

Adamski


After dinking around with it some more, I found a solution that lets you draw arbitrarily on the image after JFreeChart is done with it, so I'll post it here for posterity. In my case, I was writing the chart to an OutputStream, so my code looked something like this:

BufferedImage chartImage = chart.createBufferedImage(width, height, null);
Graphics2D g = (Graphics2D) chartImage.getGraphics();
/* arbitrary drawing happens here */
EncoderUtil.writeBufferedImage(chartImage, ImageFormat.PNG, outputStream);
like image 26
Robert J. Walker Avatar answered May 31 '26 22:05

Robert J. Walker



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!