Search code examples
javarenderjfreechartlegend

How to display legend for Pie Chart in columns?


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


Solution

  • 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;
    }