开发者

Decorating a JFreeChart

I would like to decorate all my generated JF开发者_StackOverflow社区reeCharts 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.


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.


Take a look at this forum post here:

http://www.jfree.org/phpBB2/viewtopic.php?f=3&t=27939

That uses an ImageIcon as a watermark:

ImageIcon icon = new ImageIcon(new URL(watermarkUrl));
Image image = icon.getImage();
chart.setBackgroundImage(image);
chart.setBackgroundImageAlignment(Align.CENTER);
chart.getPlot().setBackgroundAlpha(0.2f);


The addSubtitle() method of org.jfree.chart.JFreeChart may be a suitable alternative.


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);


In my Experience the best way to add custom information to JFreeChart is: - Instantiate a BufferedImage of the same type of the chart; - draw on the BufferedImage ; - add the image to the current Plot, by using an XYImageAnnotation.

This is a guideline for the code:

// retrieve image type and create another BufferedImage
int imgType = chart.createBufferedImage(1,1).getType();
BufferedImage bimg = new BufferedImage(width, height, bimg.getType);

// here you can draw inside the image ( relative x & y  )
Graphics2D g2 = (Graphics2D) bimg.getGraphics();
g2.drawString("Hello, JFreeChart " + timestamp, posX, posY );

// instantiate the image annotation, then add to the plot
XYImageAnnotation a = new XYImageAnnotation( x, y, bimg, RectangleAnchor.LEFT );
chart.getPlot().addAnnotation( a );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜