2

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
novayhulk14
  • 113
  • 11

1 Answers1

1

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

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • It worked, thank you. Do you also know how to display the chart lines over the rectangles? – novayhulk14 Feb 06 '19 at 11:43
  • @novayhulk14: Glad it helped; concerning "lines over the rectangles," you may have seen a page that was cached before my [update](https://stackoverflow.com/posts/54552387/revisions). – trashgod Feb 06 '19 at 18:53
  • Thank you very much! It was exactly what I wanted :) – novayhulk14 Feb 07 '19 at 08:28