Search code examples
javaswingjfreechart

How can I draw a filled rectangle in JFreeChart?


I'm making a little application using Swing and JFreeChart. I have to display an XYLineChart, and I want to draw some filled rectangles over it. I've used the XYShapeAnnotation to draw the rectangles, and I've tried to fill them with Graphics2D, but it doesn't work. I get the rectangle displayed over the chart, but not filled. The code looks like this:

Shape rectangle = new Rectangle2D.Double(0, 0, 7, 1);
g2.fill(rectangle);
XYShapeAnnotation shapeAnnotation = new XYShapeAnnotation(rectangle, new BasicStroke(2.f), Color.BLACK);
shapeAnnotation.setToolTipText("1");
plot.addAnnotation(shapeAnnotation);

I think the problem is that the filled rectangle position is not relative to the chart, but I don't really know how to fix this. I've also wanted to know if it's possible to display the lines in the chart over the rectangles, because I don't find any way to do it.


Solution

  • Use the XYShapeAnnotation constructor that allows you to specify both outlinePaint and fillPaint. You probably want something like this:

    XYShapeAnnotation shapeAnnotation = new XYShapeAnnotation(
        rectangle, new BasicStroke(2.f), Color.BLACK, Color.BLACK);
    

    As a concrete example based on this answer, the following change produces the result shown:

     renderer.addAnnotation(new XYShapeAnnotation(ellipse, stroke, color, color));
    

    image1

    To display the lines in the chart over the rectangles, specify the background layer for the annotation, as shown here.

     renderer.addAnnotation(new XYShapeAnnotation(
         ellipse, stroke, color, color), Layer.BACKGROUND);
    

    image2