Jfreechart - how to add legend element with dash?

I want to add a legend element with a dash (-) to indicate some series in my diagram. The default form provided is only Plot.DEFAULT_LEGEND_ITEM_CIRCLE and Plot.DEFAULT_LEGEND_ITEM_BOX. Is there something like Plot.DEFAULT_LEGEND_ITEM_LINE? How to create it?

+4
source share
1 answer

You can create your own source of legend elements. Assuming you have a set of elements matching 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 diagram and add a new one:

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

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

+5
source

Source: https://habr.com/ru/post/1368884/


All Articles