4

I want to add a legend item with a dash (-) to denote some series in my chart. The default shape provided are only Plot.DEFAULT_LEGEND_ITEM_CIRCLE and Plot.DEFAULT_LEGEND_ITEM_BOX. Is there something like Plot.DEFAULT_LEGEND_ITEM_LINE ? How to create one ?

sam
  • 651
  • 3
  • 9
  • 16

1 Answers1

6

You can create your own legend item source. Assuming you have a collection of elements corresponding to the legends you want to display called legendKeys:

class LineLegendItemSource implements LegendItemSource {
    public LegendItemCollection getLegendItems() {
     LegendItemCollection itemCollection = new LegendItemCollection();
     for (Comparable comparable : legendKeys) {
        Paint paint = // get the paint you want
        LegendItem item = new LegendItem("string to display", 
                                         "description", 
                                         "tooltip", 
                                         "url", 
                                         new Line2D.Double(0, 5, 10, 5), paint);
        itemCollection.add(item);
     }
     return itemCollection; 
  }
}

Then you need to remove the old legends from the chart, and add the new:

JFreeChart chart = // your chart 
chart.removeLegend();
LegendTitle legend = new LegendTitle(new LineLegendItemSource());
chart.addLegend(legend);

As you can see the LegendItem constructor takes a shape, so you can basically draw whatever you want in there.

Jes
  • 2,748
  • 18
  • 22