Search code examples
javajfreechart

Getting Assigned Paint for TimeSeries


I am obviously not understanding the documentation for the getSeriesPaint method. I have the TimeSeries object and I want to get the color being used to render it. However, it seems like I am in a catch-22. I need to know the series index (getIndex), but to find that I need to know the series time period. However, to find the series time period, I need to know the index. I'm looking to do something like this:

Color color=(Color) r1.getSeriesPaint(arg0);

where r1 is the XYLineAndShapeRenderer. What do I use for arg0 given the TimeSeries object?


Solution

  • Because XYLineAndShapeRenderer is an XYItemRenderer, it invokes the AbstractRenderer method getItemPaint(), which "Returns the paint used to color data items as they are drawn." Note that "The default implementation passes control to the lookupSeriesPaint() method." Starting from this example, the following fragment obtains the dataset and renderer from the chart. It then enumerates the series paints—shades of red and blue seen in the image:

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    TimeSeriesCollection tsc = (TimeSeriesCollection) plot.getDataset();
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    for (int i = 0; i < tsc.getSeriesCount(); i++) {
        System.out.println(renderer.lookupSeriesPaint(i));
    }
    

    Console:

    java.awt.Color[r=255,g=85,b=85]
    java.awt.Color[r=85,g=85,b=255]
    

    image

    Alternatively, consider a custom DrawingSupplier, mentioned here.