I have a PieChart with many sections, legend for this PieChart renders as one row. How to render legend as two columns?
Asked
Active
Viewed 7,926 times
2 Answers
9
The method getLegendItem()
, seen here, provides all the information needed to render a legend item in any Container
you choose. GridLayout(0, 2)
will arrange them in two columns for any number of rows. To suppress the existing legend, set legend
to false
when you call your chart factory; the items will still be available, as suggested here.
Addendum: Based on PieChartDemo1
, this fragment uses the getLegendItems().iterator
and a variation of this ColorIcon
.
public static JPanel createDemoPanel() {
JPanel panel = new JPanel();
JFreeChart chart = createChart(createDataset());
panel.add(new ChartPanel(chart));
panel.add(createLegendPanel((PiePlot) chart.getPlot()));
return panel;
}
private static JPanel createLegendPanel(PiePlot plot) {
JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));
Iterator iterator = plot.getLegendItems().iterator();
while (iterator.hasNext()) {
LegendItem item = (LegendItem) iterator.next();
JLabel label = new JLabel(item.getLabel());
label.setIcon(new ColorIcon(8, item.getFillPaint()));
panel.add(label);
}
return panel;
}
-
Also consider a `PlotChangeListener` to update the legend panel. – trashgod Nov 11 '12 at 18:24
2
Have a look at this forum thread on Legend Alignment, also in the (web archive).
Seems like something you are looking for. If not, please post some more information or screenshots of what you have and what you need.
-
Unfortunately, this only works for old versions of jfreechart... But at least it shows how one could create another multi column legend class for newer versions of jfc. :) +1 – brimborium Nov 09 '12 at 13:42
-
1@brimborium oh, I saw that the thread is some years old, but I didn't actually check the code. still a push in the right direction i guess – moeTi Nov 09 '12 at 13:47
-
-
-
1@moeTi: Thanks! I supplemented your web archive link with a link to the original forum thread. – trashgod Jan 07 '20 at 18:52