Java – jfreechart – change sample of colors in legend

javajfreechartlegend

Can someone tell me how to change samples of series color in legend in jfreechart. What I have now is small line of series color eg:
Example
I would like to have square sample of those colors. Here is an example
Example

Can someone help me?

Ok I found the solution. At least I think. Of course there is no simple way to do this. There is now, you know, setShape(square) method, that will do the trick, at least i haven't found one.

Basicly XY chart and time chart have "line style" legend by default in contrary to bar chart for example (if has square legend by default). So I had to remove current legend and create new one with square samples of color and this new legend add to my time chart.

LegendItemCollection legend = new LegendItemCollection();    
for (int i = 0; i < seriecCount; ++i) {
    chart.getXYPlot().getRenderer().setSeriesPaint(i, colorPalette.get(i));
    LegendItem li = new LegendItem(data.getSeriesName(i), "-", null, null, Plot.DEFAULT_LEGEND_ITEM_BOX, colorPalette.get(i));
    legend.add(li);
}  
chart.getXYPlot().setFixedLegendItems(legend);

Thanks for attention. I hope it will help someone.

Best Answer

Generating your own legend, as you do above, is a perfectly acceptable way of doing things in JFreeChart. If you didn't want to do it, you can also define your own renderer with the lookupLegendShape() method overridden.

thePlot.setRenderer(new XYLineAndShapeRenderer()
      {
         public Shape lookupLegendShape(int series)
         {
            return new Rectangle(15, 15);
         }
      });
Related Topic