Search code examples
jfreechart

XYItemRenderer::setSeriesPaint() does not set the color of chart line


I am trying to modify the JFreeChart sample code in PriceVolumeDemo1.java for my own use. (I'm sure nobody has all the JFreeChart demos memorized, I mention it only for completeness.) It is a chart with a line representing price and bars representing volume. The line in the demo is red, and the bars are blue. I am trying to reverse that (blue line and red bars). I am attempting to do so with XYBarRenderer::setSeriesPaint() and XYItemRenderer::setSeriesPaint(). See the code below.

The lines I have modified in my attempt to change the colors follow the comments in the /* */ blocks.

XYBarRenderer::setSeriesPaint() works as expected, setting the bars to red. But XYItemRenderer::setSeriesPaint() does not set the line to blue. Can someone see what I am doing wrong?

private static JFreeChart createChart() {

    XYDataset priceData = createPriceDataset();
    String title = "Eurodollar Futures Contract (MAR03)";
    JFreeChart chart = ChartFactory.createTimeSeriesChart(
        title,
        "Date",
        "Price",
        priceData,
        true,
        true,
        false
    );
    XYPlot plot = (XYPlot) chart.getPlot();
    NumberAxis rangeAxis1 = (NumberAxis) plot.getRangeAxis();
    rangeAxis1.setLowerMargin(0.40);  // to leave room for volume bars
    DecimalFormat format = new DecimalFormat("00.00");
    rangeAxis1.setNumberFormatOverride(format);

    XYItemRenderer renderer1 = plot.getRenderer();
    /* This does NOT set the line graph to blue. */
    renderer1.setSeriesPaint(0, Color.BLUE);

    renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));

    NumberAxis rangeAxis2 = new NumberAxis("Volume");
    rangeAxis2.setUpperMargin(1.00);  // to leave room for price line
    plot.setRangeAxis(1, rangeAxis2);
    plot.setDataset(1, createVolumeDataset());
    plot.setRangeAxis(1, rangeAxis2);
    plot.mapDatasetToRangeAxis(1, 1);
    XYBarRenderer renderer2 = new XYBarRenderer(0.20);
    renderer2.setBaseToolTipGenerator(
        new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("d-MMM-yyyy"),
            new DecimalFormat("0,000.00")));
    plot.setRenderer(1, renderer2);
    ChartUtilities.applyCurrentTheme(chart);
    renderer2.setBarPainter(new StandardXYBarPainter());
    renderer2.setShadowVisible(false);
    /* This sets the bar colors to red. */
    renderer2.setSeriesPaint(0, Color.RED);
    return chart;

}

Solution

  • Apply the ChartTheme right after the chart is created, before making any calls to setSeriesPaint().

    JFreeChart chart = ChartFactory.createTimeSeriesChart(...);
    ChartUtilities.applyCurrentTheme(chart);
    XYPlot plot = (XYPlot) chart.getPlot();