如何在 JFreeChart 中绘制一个填充的矩形?

How can I draw a filled rectangle in JFreeChart?

我正在使用 Swing 和 JFreeChart 制作一个小应用程序。我必须显示一个 XYLineChart,并且我想在其上绘制一些填充的矩形。我已经使用 XYShapeAnnotation 绘制矩形,并尝试用 Graphics2D 填充它们,但它不起作用。我在图表上显示了矩形,但未填充。代码如下所示:

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

我认为问题是填充的矩形位置与图表无关,但我真的不知道如何解决这个问题。我也想知道是否可以在矩形上方显示图表中的线条,因为我找不到任何方法。

使用 XYShapeAnnotation 构造函数允许您指定 both outlinePaint and fillPaint .你可能想要这样的东西:

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

作为基于此 的具体示例,以下更改会产生所示结果:

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

要在图表 上方 矩形上显示线条,请为注释指定背景图层,如图 here

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