5.10 实例讲解

5.10.1 体会

也分为三层界面显示层、数据层、控制层。

  • 数据层比较复杂。每个图形有不同的数据类型。Dataset类控制。
  • 控制层Plot,饼图使用PiePlot设置显示的图形的面貌的控制,JFreeChart最丰富的功能。
  • 设置片区颜色
  • 设置标签(文本格式、背景颜色等)
  • 设置是否取出某块。
  • 设置饼图是否为圆形
  • 设置饼图旋转。
  • 显示层JFreeChart使用数据、控制直接将数据显示出来。

5.10.2 类PieChartDemo1.java

效果图如下:

代码编写典型的使用了面对对象的方法:

全部代码如下:

package demo;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class PieChartDemo1 extends ApplicationFrame {
    /**
    *
    */
    private static final long serialVersionUID = 2598557557724085474L;
    public PieChartDemo1(String string) {
        super(string);
        JPanel jpanel = createDemoPanel();
        jpanel.setPreferredSize(new Dimension(500, 270));
        setContentPane(jpanel);
    }
    private static PieDataset createDataset() {
        DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
        defaultpiedataset.setValue("One", new Double(43.2));
        defaultpiedataset.setValue("Two", new Double(10.0));
        defaultpiedataset.setValue("Three", new Double(27.5));
        defaultpiedataset.setValue("Four", new Double(17.5));
        defaultpiedataset.setValue("Five", new Double(11.0));
        defaultpiedataset.setValue("Six", new Double(19.4));
        return defaultpiedataset;
    }
    private static JFreeChart createChart(PieDataset piedataset) {
        JFreeChart jfreechart = ChartFactory.createPieChart("Pie Chart Demo 1",
        piedataset, true, true, false);
        TextTitle texttitle = jfreechart.getTitle();
        texttitle.setToolTipText("A title tooltip!");
        PiePlot pieplot = (PiePlot) jfreechart.getPlot();
        pieplot.setLabelFont(new Font("Arial Black", 0, 20));
        pieplot.setNoDataMessage("No data available");
        pieplot.setCircular(false);
        pieplot.setLabelGap(0.02);
        return jfreechart;
    }
    public static JPanel createDemoPanel() {
        JFreeChart jfreechart = createChart(createDataset());
        return new ChartPanel(jfreechart);
    }
    public static void main(String[] strings) {
        PieChartDemo1 piechartdemo1 = new PieChartDemo1("Pie Chart Demo 1");
        piechartdemo1.pack();
        RefineryUtilities.centerFrameOnScreen(piechartdemo1);
        piechartdemo1.setVisible(true);
    }
}

5.10.3 类PieChartDemo2.java

功能:

“取出“片区显示。

效果:

代码:

private static JFreeChart createChart(PieDataset piedataset) {
    JFreeChart jfreechart = ChartFactory.createPieChart("PieChart Demo 2", piedataset, true, true, false);
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    pieplot.setSectionPaint("One", new Color(160, 160, 255));
    pieplot.setSectionPaint("Two", new Color(128, 128, 223));
    pieplot.setSectionPaint("Three", new Color(96, 96, 191));
    pieplot.setSectionPaint("Four", new Color(64, 64, 159));
    pieplot.setSectionPaint("Five", new Color(32, 32, 127));
    pieplot.setSectionPaint("Six", new Color(0, 0, 111));
    pieplot.setNoDataMessage("No data available");
    pieplot.setExplodePercent("Two", 0.5);
    pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2} percent)"));
    pieplot.setLabelBackgroundPaint(new Color(220, 220, 220));
    pieplot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("Tooltip for legend item {0}"));
    return jfreechart;
}

程序代码说明:

  • setSectionPaint("One", new Color(160, 160, 255)):设置某个片区的填充颜色。第一个参数为片区的标识,第二个参数为色值。
  • setNoDataMessage("No data available"):设置dataset为null时显示的提示信息。
  • setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({2} percent)")):设置标签显示的格式。
  • setLabelBackgroundPaint(new Color(220, 220, 220)):设置标签的背景颜色。
  • setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("Tooltip for legend item {0}")):设置鼠标滑过图表是显示鼠标当前片区的提示信息。
  • pieplot.setExplodePercent("Two", 0.5):将第2个片区取出显示。后面一个参数是取出的距离,是一个比例数。

5.10.4 类PieChartDemo3.java

功能:

显示了dataset为空时,设置的提示信息。

效果:

代码:

private static JFreeChart createChart(PieDataset piedataset) {
    JFreeChart jfreechart = ChartFactory.createPieChart("Pie Chart Demo 3",
    null, true, true, false);
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    pieplot.setNoDataMessage("没有有效的数据显示!");
    pieplot.setNoDataMessageFont(new Font("黑体", 2, 20));
    pieplot.setNoDataMessagePaint(Color.red);
    return jfreechart;
}

程序代码说明:

  • setNoDataMessage("没有有效的数据显示!"):设置提示信息内容。
  • setNoDataMessageFont(new Font("Serif", 2, 10)):设置提示信息的字体和大小。
  • setNoDataMessagePaint(Color.red):设置提示信息字体的颜色。

5.10.5 类PieChartDemo4.java

功能:

带有按钮的图表,通过对dataset的排序,可以改变片区的位置。

效果:

代码:

public void actionPerformed(ActionEvent actionevent) {
    String string = actionevent.getActionCommand();
    if ("BY_KEY".equals(string)) {
        if (!ascendingByKey) {
            dataset.sortByKeys(SortOrder.ASCENDING);
            ascendingByKey = true;
        } else {
            dataset.sortByKeys(SortOrder.DESCENDING);
            ascendingByKey = false;
        }
    } else if ("BY_VALUE".equals(string)) {
        if (!ascendingByValue) {
            dataset.sortByValues(SortOrder.ASCENDING);
            ascendingByValue = true;
        } else {
            dataset.sortByValues(SortOrder.DESCENDING);
            ascendingByValue = false;
        }
    } else if ("RANDOM".equals(string)) {
        ArrayList arraylist = new ArrayList(dataset.getKeys());
        Collections.shuffle(arraylist);
        DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
        Iterator iterator = arraylist.iterator();
        while (iterator.hasNext()) {
            Comparable comparable = (Comparable) iterator.next();
            defaultpiedataset.setValue(comparable, dataset
            .getValue(comparable));
        }
        PiePlot pieplot = (PiePlot) chart.getPlot();
        pieplot.setDataset(defaultpiedataset);
        dataset = defaultpiedataset;
    }
}

程序代码说明:

  • dataset.sortByKeys(SortOrder.ASCENDING);通过片区的关键值进行升序排序。
  • dataset.sortByValues(SortOrder.DESCENDING);通过片区的值进行降序排序。

5.10.6 类PieChartDemo5.java

功能:

右边两个饼图为原形的,而左边两个为椭圆形的。

效果:

代码:

public static JPanel createDemoPanel() {
    JPanel jpanel = new JPanel(new GridLayout(2, 2));
    DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
    defaultpiedataset.setValue("Section 1", 23.3);
    defaultpiedataset.setValue("Section 2", 56.5);
    defaultpiedataset.setValue("Section 3", 43.3);
    defaultpiedataset.setValue("Section 4", 11.1);
    //
    JFreeChart jfreechart = ChartFactory.createPieChart("Chart 1",
        defaultpiedataset, false, false, false);
    jfreechart.addSubtitle(new TextTitle("setCircular(true);", new Font(
        "Dialog", 0, 12)));
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    pieplot.setCircular(true);
    //
    JFreeChart jfreechart_0_ = ChartFactory.createPieChart("Chart 2",
        defaultpiedataset, false, false, false);
    jfreechart_0_.addSubtitle(new TextTitle("setCircular(false);",
        new Font("Dialog", 0, 12)));
    PiePlot pieplot_1_ = (PiePlot) jfreechart_0_.getPlot();
    pieplot_1_.setCircular(false);
    //
    JFreeChart jfreechart_2_ = ChartFactory.createPieChart3D("Chart 3",
        defaultpiedataset, false, false, false);
    jfreechart_2_.addSubtitle(new TextTitle("setCircular(true);", new Font(
        "Dialog", 0, 12)));
    PiePlot3D pieplot3d = (PiePlot3D) jfreechart_2_.getPlot();
    pieplot3d.setForegroundAlpha(0.6F);
    pieplot3d.setCircular(true);
    //
    JFreeChart jfreechart_3_ = ChartFactory.createPieChart3D("Chart 4",
        defaultpiedataset, false, false, false);
    jfreechart_3_.addSubtitle(new TextTitle("setCircular(false);",
        new Font("Dialog", 0, 12)));
    PiePlot3D pieplot3d_4_ = (PiePlot3D) jfreechart_3_.getPlot();
    pieplot3d_4_.setForegroundAlpha(0.6F);
    pieplot3d_4_.setCircular(false);
    jpanel.add(new ChartPanel(jfreechart));
    jpanel.add(new ChartPanel(jfreechart_0_));
    jpanel.add(new ChartPanel(jfreechart_2_));
    jpanel.add(new ChartPanel(jfreechart_3_));
    jpanel.setPreferredSize(new Dimension(800, 600));
    return jpanel;
}

程序代码说明:

  • pieplot.setCircular(true):设置饼图为圆形。
  • jpanel.add方法可以添加多个图形的panel

5.10.7 类PieChartDemo6.java

功能:

显示饼图对零值和null值的处理。

效果:

代码:

public static JPanel createDemoPanel() {
JPanel jpanel = new JPanel(new GridLayout(2, 2));
    JFreeChart jfreechart = createChart("Pie Chart 1", createDataset());
    Font font = new Font("Dialog", 0, 12);
    jfreechart.addSubtitle(new TextTitle(
        "Ignore nulls: false; Ignore zeros: false;", font));
    JFreeChart jfreechart_0_ = createChart("Pie Chart 2", createDataset());
    jfreechart_0_.addSubtitle(new TextTitle(
        "Ignore nulls: true; Ignore zeros: false;", font));
    PiePlot pieplot = (PiePlot) jfreechart_0_.getPlot();
    pieplot.setIgnoreNullValues(true);
    pieplot.setIgnoreZeroValues(false);
    JFreeChart jfreechart_1_ = createChart("Pie Chart 3", createDataset());
    jfreechart_1_.addSubtitle(new TextTitle(
        "Ignore nulls: false; Ignore zeros: true;", font));
    PiePlot pieplot_2_ = (PiePlot) jfreechart_1_.getPlot();
    pieplot_2_.setIgnoreNullValues(false);
    pieplot_2_.setIgnoreZeroValues(true);
    JFreeChart jfreechart_3_ = createChart("Pie Chart 4", createDataset());
    jfreechart_3_.addSubtitle(new TextTitle(
        "Ignore nulls: true; Ignore zeros: true;", font));
    PiePlot pieplot_4_ = (PiePlot) jfreechart_3_.getPlot();
    pieplot_4_.setIgnoreNullValues(true);
    pieplot_4_.setIgnoreZeroValues(true);
    jpanel.add(new ChartPanel(jfreechart));
    jpanel.add(new ChartPanel(jfreechart_0_));
    jpanel.add(new ChartPanel(jfreechart_1_));
    jpanel.add(new ChartPanel(jfreechart_3_));
    return jpanel;
}

程序代码说明:

  • pieplot.setIgnoreNullValues(true):设置饼图忽略null值,即是null值将不显示。
  • pieplot.setIgnoreZeroValues(false);设置饼图不忽略零值。即图表中显示出零值。

5.10.8 类PieChartDemo7.java

功能:

图表能够旋转,标签也随之移动。

效果:

代码:

public static JPanel createDemoPanel() {
    PieDataset piedataset = createDataset(14);
    JFreeChart jfreechart = ChartFactory.createPieChart("Pie Chart Demo 7",
        piedataset, false, true, false);
    jfreechart.setBackgroundPaint(new Color(222, 222, 255));
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    pieplot.setBackgroundPaint(Color.white);
    pieplot.setCircular(true);
    pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator(
        "{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat
        .getPercentInstance()));
    pieplot.setNoDataMessage("No data available");
    ChartPanel chartpanel = new ChartPanel(jfreechart);
    chartpanel.setPreferredSize(new Dimension(500, 270));
    Rotator rotator = new Rotator(pieplot);
    rotator.start();
    return chartpanel;
}

程序代码说明:

  • 使用Rotator对象,旋转饼图。代码如上。

5.10.9 类PieChartDemo8.java

功能:

编写自定义标签产生器,将Two标签不显示。

效果:

代码:

private static JFreeChart createChart(PieDataset piedataset) {
    JFreeChart jfreechart = ChartFactory.createPieChart("Pie Chart Demo 8",
    piedataset, false, true, false);
    PiePlot pieplot = (PiePlot) jfreechart.getPlot();
    pieplot.setLabelGenerator(new CustomLabelGenerator());
    return jfreechart;
}
static class CustomLabelGenerator implements PieSectionLabelGenerator {
    public String generateSectionLabel(PieDataset piedataset,
    Comparable comparable) {
    String string = null;
        if (piedataset != null && !comparable.equals("Two"))
            string = comparable.toString();
        return string;
    }
    public AttributedString generateAttributedSectionLabel(
        PieDataset piedataset, Comparable comparable) {
        Object object = null;
        String string = comparable.toString();
        String string_0_ = (string + " : " + String.valueOf(piedataset
            .getValue(comparable)));
        AttributedString attributedstring = new AttributedString(string_0_);
        attributedstring.addAttribute(TextAttribute.WEIGHT,
        TextAttribute.WEIGHT_BOLD, 0, string.length() - 1);
        return attributedstring;
    }
}

程序代码说明:

  • 自定义CustomLabelGenerator,必须实现接口PieSectionLabelGenerator

5.10.10 类PieChart3DDemo1.java

功能:

3D效果的饼图。

效果:

代码:

private static JFreeChart createChart(PieDataset piedataset) {
    JFreeChart jfreechart = ChartFactory.createPieChart3D(
        "Pie Chart 3D Demo 1", piedataset, true, true, false);
    PiePlot3D pieplot3d = (PiePlot3D) jfreechart.getPlot();
    pieplot3d.setStartAngle(180.0);
    pieplot3d.setDirection(Rotation.CLOCKWISE);
    pieplot3d.setForegroundAlpha(0.5F);
    pieplot3d.setNoDataMessage("No data to display");
    return jfreechart;
}

程序代码说明:

  • 使用ChartFactory的方法createPieChart3D创建3D效果的饼图。
  • setStartAngle(180.0):设置旋转角度。
  • setDirection(Rotation.CLOCKWISE):设置旋转方向,Rotation.CLOCKWISE为顺时针。
  • setForegroundAlpha(0.5F):设置图表透明图0.0~1.0范围。0.0为完全透明,1.0为完全不透明。

5.10.11 类MultiplePieChartDemo1.java

功能:

使用CategoryDataset数据集,在一个图表上产生多个饼图。

效果:

代码:

private static CategoryDataset createDataset() {
    double[][] ds = { { 3.0, 4.0, 3.0, 5.0 }, { 5.0, 7.0, 6.0, 8.0 },
        { 5.0, 7.0, Double.NaN, 3.0 }, { 1.0, 2.0, 3.0, 4.0 },
        { 2.0, 3.0, 2.0, 3.0 } };
    CategoryDataset categorydataset = DatasetUtilities
        .createCategoryDataset("Region ", "Sales/Q", ds);
    return categorydataset;
}

程序代码说明:

  • 创建CategoryDataset的方法。
private static JFreeChart createChart(CategoryDataset categorydataset) {
    JFreeChart jfreechart = ChartFactory.createMultiplePieChart(
        "Multiple Pie Chart", categorydataset, TableOrder.BY_ROW, true, true, false);
    MultiplePiePlot multiplepieplot = (MultiplePiePlot) jfreechart .getPlot();
    JFreeChart jfreechart_0_ = multiplepieplot.getPieChart();
    PiePlot pieplot = (PiePlot) jfreechart_0_.getPlot();
    pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
    pieplot.setLabelFont(new Font("SansSerif", 0, 8));
    pieplot.setInteriorGap(0.3);
    return jfreechart;
}

程序代码说明:

  • 使用ChartFactory的方法createMultiplePieChart()创建多个饼图的图表。
  • multiplepieplot.getPieChart():获得单个饼图的图表。