3

I have a PieChart with many sections, legend for this PieChart renders as one row. How to render legend as two columns?

user1581508
  • 113
  • 1
  • 8

2 Answers2

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.

legend image

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;
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
moeTi
  • 3,884
  • 24
  • 37
  • 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
  • @moeTi: Same here, but the link is dead. Can you find the original? – trashgod Sep 26 '19 at 09:32
  • @trashgod found it in wayback machine and updated the original post – moeTi Jan 07 '20 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