如何在列中显示饼图的图例?

问题描述:

我有一个包含许多部分的PieChart,此PieChart的图例呈现为一行。如何将图例渲染为两列?

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

方法 getLegendItem(),见此处,提供在任何容器中呈现图例项目所需的所有信息你选择code>。 GridLayout(0,2)将在两列中排列任意数量的行。要取消现有图例,请在调用图表工厂时将图例设置为 false ;这些项目仍然可用,如此处所示。

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.

附录:基于 PieChartDemo1 ,此片段使用 getLegendItems()。iterator 以及此 ColorIcon

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