zoukankan      html  css  js  c++  java
  • JfreeChart使用(转载)

    http://www.cnblogs.com/xingyun/

    http://www.huosen.net/archives/156.html(此篇除了struts2外,还介绍了servlet下JfreeChart的使用)

    JFreeChart的使用

     

    前提:导入需要的2个jar文件,jcommon-版本号.jar,jfreechart-版本号.jar。可以去官网下载:http://sourceforge.net/projects/jfreechart/files/

    注意:下载的Jfreechart版本不要太高,新版本对中文的显示会出问题,我自己后来下的是1.0.10的版本。

    实例一:比较简单的application版本的饼图

    复制代码
    package com.test.jfreechart;

    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartFrame;
    import org.jfree.chart.JFreeChart;
    import org.jfree.data.general.DefaultPieDataset;

    public class JFreeChartTest
    {
    public static void main(String[] args)
    {
    DefaultPieDataset dpd=new DefaultPieDataset(); //建立一个默认的饼图
    dpd.setValue("管理人员", 25); //输入数据
    dpd.setValue("市场人员", 25);
    dpd.setValue("开发人员", 45);
    dpd.setValue("其他人员", 10);

    JFreeChart chart=ChartFactory.createPieChart("某公司人员组织数据图",dpd,true,true,false);
    //可以查具体的API文档,第一个参数是标题,第二个参数是一个数据集,第三个参数表示是否显示Legend,第四个参数表示是否显示提示,第五个参数表示图中是否存在URL

    ChartFrame chartFrame=new ChartFrame("某公司人员组织数据图",chart);
    //chart要放在Java容器组件中,ChartFrame继承自java的Jframe类。该第一个参数的数据是放在窗口左上角的,不是正中间的标题。
    chartFrame.pack(); //以合适的大小展现图形
    chartFrame.setVisible(true);//图形是否可见

    }
    }
    复制代码

    运行结果如下:

    注:一个图表由以下3个部分组成:


    实例二:一个结构更加明晰的application版本的柱状图,将逻辑分装到各个函数中去。

    复制代码
    package com.test.jfreechart;

    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.axis.CategoryAxis;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.category.CategoryDataset;
    import org.jfree.data.category.DefaultCategoryDataset;
    import org.jfree.ui.ApplicationFrame;

    public class JFreeChartTest2 extends ApplicationFrame
    {
    public JFreeChartTest2(String title)
    {
    super(title);
    this.setContentPane(createPanel()); //构造函数中自动创建Java的panel面板
    }

    public static CategoryDataset createDataset() //创建柱状图数据集
    {
    DefaultCategoryDataset dataset=new DefaultCategoryDataset();
    dataset.setValue(10,"a","管理人员");
    dataset.setValue(20,"b","市场人员");
    dataset.setValue(40,"c","开发人员");
    dataset.setValue(15,"d","其他人员");
    return dataset;
    }

    public static JFreeChart createChart(CategoryDataset dataset) //用数据集创建一个图表
    {
    JFreeChart chart=ChartFactory.createBarChart("hi", "人员分布",
    "人员数量", dataset, PlotOrientation.VERTICAL, true, true, false); //创建一个JFreeChart
    chart.setTitle(new TextTitle("某公司组织结构图",new Font("宋体",Font.BOLD+Font.ITALIC,20)));//可以重新设置标题,替换“hi”标题
    CategoryPlot plot=(CategoryPlot)chart.getPlot();//获得图标中间部分,即plot
    CategoryAxis categoryAxis=plot.getDomainAxis();//获得横坐标
    categoryAxis.setLabelFont(new Font("微软雅黑",Font.BOLD,12));//设置横坐标字体
    return chart;
    }

    public static JPanel createPanel()
    {
    JFreeChart chart =createChart(createDataset());
    return new ChartPanel(chart); //将chart对象放入Panel面板中去,ChartPanel类已继承Jpanel
    }

    public static void main(String[] args)
    {
    JFreeChartTest2 chart=new JFreeChartTest2("某公司组织结构图");
    chart.pack();//以合适的大小显示
    chart.setVisible(true);

    }
    }
    复制代码

    运行结果如下:


    实例三:将chart图表转换成JPEG格式的图片的application

    复制代码
    package com.test.jfreechart;

    import java.awt.Font;
    import java.io.FileOutputStream;
    import java.io.OutputStream;

    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.ChartUtilities;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.plot.PiePlot;
    import org.jfree.chart.title.LegendTitle;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.general.DefaultPieDataset;

    public class JFreeChartTest3
    {
    public static void main(String[] args) throws Exception
    {
    JFreeChart chart=ChartFactory.createPieChart("某公司人员组织数据图",getDataset(),true,true,false);
    chart.setTitle(new TextTitle("某公司组织结构图",new Font("宋体",Font.BOLD+Font.ITALIC,20)));

    LegendTitle legend=chart.getLegend(0);//设置Legend
    legend.setItemFont(new Font("宋体",Font.BOLD,14));
    PiePlot plot=(PiePlot) chart.getPlot();//设置Plot
    plot.setLabelFont(new Font("隶书",Font.BOLD,16));

    OutputStream os = new FileOutputStream("company.jpeg");//图片是文件格式的,故要用到FileOutputStream用来输出。
    ChartUtilities.writeChartAsJPEG(os, chart, 1000, 800);
    //使用一个面向application的工具类,将chart转换成JPEG格式的图片。第3个参数是宽度,第4个参数是高度。

    os.close();//关闭输出流
    }

    private static DefaultPieDataset getDataset()
    {
    DefaultPieDataset dpd=new DefaultPieDataset(); //建立一个默认的饼图
    dpd.setValue("管理人员", 25); //输入数据
    dpd.setValue("市场人员", 25);
    dpd.setValue("开发人员", 45);
    dpd.setValue("其他人员", 10);
    return dpd;
    }
    }
    复制代码

    运行结果如下,在该项目的根目录下生成了JPEG格式的图片,注意不是在webroot目录下。

    实例四:将类似实例三生成的图片嵌入到JSP页面中去。

    1.web.xml中加入以下配置信息.

    复制代码
        <servlet>
    <servlet-name>DisplayChart</servlet-name>
    <servlet-class>
    org.jfree.chart.servlet.DisplayChart <!--这个固定不变-->
    </servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>DisplayChart</servlet-name>
    <url-pattern>/DisplayChart</url-pattern>
    </servlet-mapping>
    复制代码

    2.jfreeChart.jsp

    复制代码
    <%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>

    <%@ page import="org.jfree.data.general.DefaultPieDataset,org.jfree.chart.ChartFactory
    ,org.jfree.chart.JFreeChart,org.jfree.chart.servlet.*" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>Insert title here</title>
    </head>
    <body>

    <%

    DefaultPieDataset dpd = new DefaultPieDataset();

    dpd.setValue("管理人员", 25);
    dpd.setValue("市场人员", 25);
    dpd.setValue("开发人员", 45);
    dpd.setValue("其他人员", 10);

    JFreeChart chart = ChartFactory.createPieChart("某公司组织结构图",dpd, true, false, false);

    String fileName = ServletUtilities.saveChartAsPNG(chart,800,600,session);
    //ServletUtilities是面向web开发的工具类,返回一个字符串文件名,文件名自动生成,生成好的图片会自动放在服务器(tomcat)的临时文件下(temp)

    String url = request.getContextPath() + "/DisplayChart?filename=" + fileName;
    //根据文件名去临时目录下寻找该图片,这里的/DisplayChart路径要与配置文件里用户自定义的<url-pattern>一致

    %>

    <img src="<%= url %>" width="800" height="600">


    </body>
    </html>
    复制代码

    显示结果为:


    实例五:模拟对运动项目投票然后查看投票JFreeChart图表

    原理:服务器不重启时,session结果依然保存模拟投票功能,使用struts2-jfreechart-plugin-版本号.jar插件将图表对象在action中自动渲染。

    注意:不要忘记添加struts2-jfreechart-plugin-版本号.jar到工程中。

    1.Action类:

    复制代码
    package com.test.action;

    import java.awt.Font;
    import java.util.List;
    import java.util.Map;

    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.CategoryAxis;
    import org.jfree.chart.axis.CategoryLabelPositions;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.category.CategoryDataset;
    import org.jfree.data.category.DefaultCategoryDataset;

    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;

    public class ViewResultAction extends ActionSupport
    {
    private JFreeChart chart;//这里变量名必须是chart,不能是其他变量名

    private List<String> interest; //struts会自动类型转换,将页面传递过来的值存到List中去

    public JFreeChart getChart()//getChart()方法是必须的,setChart()可以不写.
    { //在action中的chart属性的get方法中,创建chart对象,然后进行设置plot主体和颜色;以及legend颜色和字体

    chart = ChartFactory.createBarChart("兴趣统计结果", "项目", "结果", this
    .getDataset(), PlotOrientation.VERTICAL, false, false, false);

    chart.setTitle(new TextTitle("兴趣统计结果",new Font("黑体",Font.BOLD,22)));

    CategoryPlot plot = (CategoryPlot)chart.getPlot();

    CategoryAxis categoryAxis = plot.getDomainAxis();

    categoryAxis.setLabelFont(new Font("宋体",Font.BOLD,22));

    categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//设置角度

    NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();

    numberAxis.setLabelFont(new Font("宋体",Font.BOLD,22));

    return chart;
    }

    public List<String> getInterest()
    {
    return interest;
    }

    public void setInterest(List<String> interest)
    {
    this.interest = interest;
    }

    @Override
    public String execute() throws Exception
    {
    return SUCCESS;
    }

    @SuppressWarnings("unchecked")
    private void increaseResult(List<String> list)//真正在开发中是不会写在action里的,应该写在model中
    { //模拟一个临时数据库

    ActionContext context = ActionContext.getContext();//struts与servlet的耦合方式一

    Map map = context.getApplication();

    for (String str : list)
    {
    if (null == map.get(str))//表示用户第一次投票
    {
    map.put(str, 1);
    }
    else
    {
    map.put(str, (Integer) map.get(str) + 1);
    }
    }
    }

    @SuppressWarnings("unchecked")
    private CategoryDataset getDataset() //得到数据集。
    {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    this.increaseResult(this.getInterest());

    ActionContext context = ActionContext.getContext();

    Map map = context.getApplication();

    dataset.setValue((Integer) map.get("football"), "", "足球");//更新成最新值
    dataset.setValue((Integer) map.get("basketball"), "", "篮球");
    dataset.setValue((Integer) map.get("volleyball"), "", "排球");
    dataset.setValue((Integer) map.get("badminton"), "", "羽毛球");

    return dataset;
    }

    }
    复制代码


    2.Jsp页面

    复制代码
    <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    </head>

    <body>
    <h1><font color="blue">请选择喜欢的运动项目</font></h1>
    <s:form action="viewResult">
    <s:checkbox name="interest" label="足球" fieldValue="football"></s:checkbox>
    <s:checkbox name="interest" label="篮球" fieldValue="basketball"></s:checkbox>
    <s:checkbox name="interest" label="排球" fieldValue="volleyball"></s:checkbox>
    <s:checkbox name="interest" label="羽毛球" fieldValue="badminton"></s:checkbox>
    <!--
    <s:checkboxlist list="#{'computer':'计算机','math':'数学'}" name="interest" label="课程" labelposition="top"></s:checkboxlist>
    -->
    <s:submit value="提交"></s:submit>
    </s:form>


    </body>
    </html>
    复制代码

    3.struts.xml的配置

    <package name="struts2" extends="struts-default,jfreechart-default">

    注意:这里的包要继承2个。网上常用的方法是将struts2-jfreechart-plugin-版本号.jar插件解压,然后修改struts-plugin-xml中package,让它继承于struts-default包然后重新打包,再配置action中的package包,使其extends= jfreechart-default,感觉这种做法比较麻烦。还是直接继承2个包比较方便。

    <action name="viewResult" class="com.test.action.ViewResultAction">
    <result name="success" type="chart">
    <param name="height">600</param>
    <param name="width">800</param>
    </result>
    </action>

    这里<result/>标签中不需要再加入JSP页面用来跳转,会直接跳转到由chart所指定的ChartResult类来处理。

    附struts-plugin-xml文件内容:

    复制代码
    <struts> 
    <package name="jfreechart-default"> 
    <result-types> 
      <result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult"> 
        <param name="height">150</param> 
        <param name="width">200</param> 
      </result-type> 
    </result-types> 
    </package>
    </struts> 
    
    
    复制代码

    最后页面显示结果:

    JFreeChart 使用介绍

    一、简介

    JFreeChart是JAVA平台上的一个开放的图表绘制类库。它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。
    JFreeChart可生成饼图(pie charts)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(Gantt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EXCEL关联。

    二、下载安装

    1 相关网址:

    1. 官方网址 http://www.jfree.org
    2. 官方文档 http://www.jfree.org/jfreechart/api/javadoc/index.html
    3. 官方下载 http://www.jfree.org/jfreechart/download.html

    2 所需jar包:

    1. 解压jfreechart-1.0.14.zip,并打开lib文件夹;
    2. 将jfreechart-1.0.14.jar、jcommon-1.0.17.jar导入自己的工程当中;

    三、配置使用:

    下面介绍生成柱状图、饼图、折线图的简单生成方式及生成的图的展现方式,如:图片文件、jsp页面。

    1 柱状图:

    #U67f1#U72b6#U56fe
    下边的方法为生成柱状图的方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    /**
     * 创建柱状图
     * @param chartTitle 图表标题
     * @param xName      x轴标题
     * @param yName      y轴标题
     * @param dataset    数据集
     * @return
     */
    public static JFreeChart createChart(String chartTitle, String xName,
            String yName, CategoryDataset dataset) {
        /**
         * createBarChart的参数分别为:
         * 标题,横坐标标题,纵坐标标题,数据集,图标方向(水平、垂直)
         * ,是否显示图例,是否显示tooltips,是否urls
         */
        JFreeChart chart = ChartFactory.createBarChart(
                chartTitle, xName, yName,
                dataset, PlotOrientation.VERTICAL,
                true, true, false);
        /**
         * VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,
         * 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看
         */
        chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        // 背景色
        chart.setBackgroundPaint(Color.white);
        // 设置标题字体
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 14));
        // 图例背景色
        chart.getLegend().setBackgroundPaint(new Color(110, 182, 229));
        // 图例字体
        chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
     
        CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
        // 设置纵虚线可见
        //categoryPlot.setDomainGridlinesVisible(true);
        // 虚线色彩
        //categoryPlot.setDomainGridlinePaint(Color.black);
        // 设置横虚线可见
        categoryPlot.setRangeGridlinesVisible(true);
        // 虚线色彩
        categoryPlot.setRangeGridlinePaint(Color.black);
        // 设置柱的透明度
        categoryPlot.setForegroundAlpha(1.0f);
        //设置柱图背景色(注意,系统取色的时候要使用
        //16位的模式来查看颜色编码,这样比较准确)
        categoryPlot.setBackgroundPaint(new Color(110, 182, 229));
     
        /*
         * categoryPlot.setRangeCrosshairVisible(true);
         * categoryPlot.setRangeCrosshairPaint(Color.blue);
         */
     
        // 纵坐标--范围轴
        NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
        // 纵坐标y轴坐标字体
        numberAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
        // 纵坐标y轴标题字体
        numberAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
        // 设置最高的一个 Item 与图片顶端的距离
        // numberAxis.setUpperMargin(0.5);
        // 设置最低的一个 Item 与图片底端的距离
        // numberAxis.setLowerMargin(0.5);
        // 设置刻度单位 为Integer
        numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
     
        // 横坐标--类别轴、域
        CategoryAxis categoryAxis = categoryPlot.getDomainAxis();
        // 横坐标x轴坐标字体
        categoryAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
        // 横坐标x轴标题字体
        categoryAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
        // 类别轴的位置,倾斜度
        categoryAxis.setCategoryLabelPositions(
                CategoryLabelPositions.createUpRotationLabelPositions(
                        0.5235987755982988D));
        //横轴上的 Lable
        //categoryAxis.setMaximumCategoryLabelWidthRatio(0.6f);
        //是否完整显示
        //设置距离图片左端距离
        categoryAxis.setLowerMargin(0.1D);
        // 设置距离图片右端距离
        categoryAxis.setUpperMargin(0.1D);
     
        // 渲染 - 中间的部分
        BarRenderer barRenderer = (BarRenderer) categoryPlot.getRenderer();
        // 设置柱子宽度
        barRenderer.setMaximumBarWidth(0.05);
        // 设置柱子高度
        barRenderer.setMinimumBarLength(0.2);
        // 设置柱子边框颜色
        barRenderer.setBaseOutlinePaint(Color.BLACK);
        // 设置柱子边框可见
        barRenderer.setDrawBarOutline(true);
        // 设置柱的颜色
        barRenderer.setSeriesPaint(0, new Color(0, 255, 0));
        barRenderer.setSeriesPaint(1, new Color(0, 0, 255));
        barRenderer.setSeriesPaint(2, new Color(255, 0, 0));
        // 设置每个柱之间距离
        barRenderer.setItemMargin(0.2D);
        // 显示每个柱的数值,并修改该数值的字体属性
        barRenderer.setIncludeBaseInRange(true);
        barRenderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator());
        barRenderer.setBaseItemLabelsVisible(true);
     
        return chart;
    }

    柱状图的数据集:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    /**
     * 柱状图数据集
     *
     * @return
     */
    public static CategoryDataset createDataset() {
        String str1 = "Java EE开发";
        String str2 = "IOS开发";
        String str3 = "Android开发";
        String str4 = "1月";
        String str5 = "2月";
        String str6 = "3月";
        String str7 = "4月";
        String str8 = "5月";
     
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
     
        dataset.addValue(1.0D, str1, str4);
        dataset.addValue(4.0D, str1, str5);
        dataset.addValue(3.0D, str1, str6);
        dataset.addValue(5.0D, str1, str7);
        dataset.addValue(5.0D, str1, str8);
     
        dataset.addValue(5.0D, str2, str4);
        dataset.addValue(7.0D, str2, str5);
        dataset.addValue(6.0D, str2, str6);
        dataset.addValue(8.0D, str2, str7);
        dataset.addValue(4.0D, str2, str8);
     
        dataset.addValue(4.0D, str3, str4);
        dataset.addValue(3.0D, str3, str5);
        dataset.addValue(2.0D, str3, str6);
        dataset.addValue(3.0D, str3, str7);
        dataset.addValue(6.0D, str3, str8);
        return dataset;
    }

    2 饼图:

    #U997c#U72b6#U56fe
    下边为饼图的生成方法和数据的生成方式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    /**
     * 生成饼图
     * @param chartTitle 图的标题
     * @param dataset 数据集
     * @param pieKeys 分饼的名字集
     * @return
     */
    public static JFreeChart createPieChart3D(
            String chartTitle,
            PieDataset dataset,
            String[] pieKeys) {
     
        JFreeChart chart = ChartFactory.createPieChart3D(
                chartTitle,
                dataset,
                true,//显示图例
                true,
                false);
     
        //关闭抗锯齿,是字体清晰
        chart.getRenderingHints().put(
                RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        chart.setTextAntiAlias(false);
        //图片背景色
        chart.setBackgroundPaint(Color.white);
        //设置图标题的字体重新设置title
        Font font = new Font("隶书", Font.BOLD, 25);
        chart.getTitle().setFont(font);
        /*TextTitle title = new TextTitle(chartTitle);
        title.setFont(font);
        chart.setTitle(title);*/
        //设置图例字体
        chart.getLegend().setItemFont(new Font("宋体",Font.PLAIN,14));
     
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        // 图片中显示百分比:默认方式
     
        // 指定饼图轮廓线的颜色
        // plot.setBaseSectionOutlinePaint(Color.BLACK);
        // plot.setBaseSectionPaint(Color.BLACK);
     
        // 设置无数据时的信息
        plot.setNoDataMessage("无对应的数据,请重新查询。");
     
        // 设置无数据时的信息显示颜色
        plot.setNoDataMessagePaint(Color.red);
     
        // 图片中显示百分比:自定义方式,{0} 表示选项,
        //{1} 表示数值, {2} 表示所占比例 ,小数点后两位
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}={1}({2})", NumberFormat.getNumberInstance(),
                new DecimalFormat("0.00%")));
        //图片显示字体
        plot.setLabelFont(new Font("宋体", Font.TRUETYPE_FONT, 12));
     
        // 图例显示百分比:自定义方式, {0} 表示选项,
        //{1} 表示数值, {2} 表示所占比例
        plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}={1}({2})"));
     
        // 指定图片的透明度(0.0-1.0)
        plot.setForegroundAlpha(0.65f);
        // 指定显示的饼图上圆形(false)还椭圆形(true)
        plot.setCircular(false, true);
     
        // 设置第一个 饼块section 的开始位置,默认是12点钟方向
        plot.setStartAngle(90);
     
        // // 设置分饼颜色
        plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144));
        plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144));
     
        return chart;
    }
    // 饼状图 数据集
    public static PieDataset getDataPieSetByUtil(double[] data,
            String[] datadescription) {
     
        if (data != null && datadescription != null) {
            if (data.length == datadescription.length) {
                DefaultPieDataset dataset = new DefaultPieDataset();
                for (int i = 0; i < data.length; i++) {
                    dataset.setValue(datadescription[i], data[i]);
                }
                return dataset;
            }
        }
        return null;
    }

    3 折线图:

    #U6298#U7ebf#U56fe
    下边为折线图的生成方法,其中,数据集的生成方式和柱状图类似:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    /**
     * 生成折线图
     * @param chartTitle 图的标题
     * @param x          横轴标题
     * @param y          纵轴标题
     * @param dataset    数据集
     * @return
     */
    public static JFreeChart createLineChart(
            String chartTitle, String x,
            String y, CategoryDataset dataset) {
     
        // 构建一个chart
        JFreeChart chart = ChartFactory.createLineChart(
                chartTitle,
                x,
                y,
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);
        //字体清晰
        chart.setTextAntiAlias(false);
        // 设置背景颜色
        chart.setBackgroundPaint(Color.WHITE);
     
        // 设置图标题的字体
        Font font = new Font("隶书", Font.BOLD, 25);
        chart.getTitle().setFont(font);
     
        // 设置面板字体
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        // 设置图示的字体
        chart.getLegend().setItemFont(labelFont);
     
        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
        // x轴 // 分类轴网格是否可见
        categoryplot.setDomainGridlinesVisible(true);
        // y轴 //数据轴网格是否可见
        categoryplot.setRangeGridlinesVisible(true);
        categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩
        categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩
        categoryplot.setBackgroundPaint(Color.lightGray);// 折线图的背景颜色
     
        // 设置轴和面板之间的距离
        // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
     
        // 横轴 x
        CategoryAxis domainAxis = categoryplot.getDomainAxis();
        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值
        // domainAxis.setLabelPaint(Color.BLUE);//轴标题的颜色
        // domainAxis.setTickLabelPaint(Color.BLUE);//轴数值的颜色
     
        // 横轴 lable 的位置 横轴上的 Lable 45度倾斜 DOWN_45
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
     
        // 设置距离图片左端距离
        domainAxis.setLowerMargin(0.0);
        // 设置距离图片右端距离
        domainAxis.setUpperMargin(0.0);
     
        // 纵轴 y
        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
        numberaxis.setLabelFont(labelFont);
        numberaxis.setTickLabelFont(labelFont);
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        numberaxis.setAutoRangeIncludesZero(true);
     
        // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot
                .getRenderer();
        lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
        lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
     
        // 显示折点数据
        lineandshaperenderer
                .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        lineandshaperenderer.setBaseItemLabelsVisible(true);
     
        return chart;
    }

    4 图表的显示方式:

    我总结了三种使用情况,分别为:
    ①生成图片到指定目录的方式;
    ②在servlet中使用,并在jsp页面中显示图片;
    ③在struts2中使用,并在jsp页面中显示图片;

    第一种

    第一种为生成指定的图片到指定的目录
    需要用到ChartUtilities类的writeChartAsPNG方法,具体使用方式如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    FileOutputStream fosChart = null;
    try {
        //文件夹不存在则创建
        File file = new File(CHART_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String chartName = CHART_PATH + charName;
        fosChart = new FileOutputStream(chartName);
        //高宽的设置影响椭圆饼图的形状
        ChartUtilities.writeChartAsPNG(fosChart, chart, 500, 230);
        return chartName;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fosChart.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    其中,CHART_PATH为文件路径,charName为生成图的名称

    第二种

    第二种为在servlet中使用,需要配置servlet,生成的图片会自动存放至tomcat服务器的temp临时文件夹下,具体如下:
    首先配置访问图片的servlet的请求:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!-- 配置jfreechart 的servlet,用来访问图片的请求 web.xml-->
    <servlet>
        <servlet-name>DisplayChart</servlet-name>
        <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DisplayChart</servlet-name>
        <url-pattern>/DisplayChart</url-pattern>
    </servlet-mapping>

    然后在servlet中,使用ServletUtilities.saveChartAsPNG方法生成临时文件,并返回文件名称,客户端就可以根据url去访问临时图片了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //ServletUtilities是面向web开发的工具类,返回一个字符串文件名,
    //文件名自动生成,生成好的图片会自动放在服务器的临时文件下(temp)
    String filename = ServletUtilities.saveChartAsPNG(
            chart, 800, 400, null, request.getSession());
     
    //根据文件名去临时目录下寻找该图片,
    //这里的/DisplayChart路径要与配置文件里用户自定义的一致
    String graphURL = request.getContextPath() +
            "/DisplayChart?filename=" + filename;
     
    request.setAttribute("imgurl", graphURL);
    request.getRequestDispatcher("index.jsp").forward(request, response);
    第三种

    第三种是在struts2中使用jfreechart,需要添加在struts2中添加jfreechart支持,即添加struts2-jfreechart-plugin-2.3.1.2.jar
    然后配置struts.xml配置文件添加:

    1
    2
    3
    800400
     
    <!-- 对应上边引用的result type chart -->

    最后,需要在Action的某方法中,给JFreeChart对象赋值,并实现get方法,即可通过页面访问该action得到图片。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    private JFreeChart chart;
    public String barchart() {
        try {
            chart = chequeService.getBarchart();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
    public JFreeChart getChart() {
        return chart;
    }
    public void setChart(JFreeChart chart) {
        this.chart = chart;
    }
  • 相关阅读:
    Do You See Me? Ethical Considerations of the Homeless
    ELDER HOMELESSNESS WHY IS THIS AN ISSUE?
    Endoflife support is lacking for homeless people
    html内联框架
    html字体
    html块 div span
    html列表
    html表格
    SQL Server管理员专用连接的使用   作为一名DBA,经常会处理一些比较棘手的服务无响应问题,鉴于事态的严重性,多数DBA可能直接用“重启”大法,以便尽快的恢复生产环境的正常运转,但是多数情况
    如何配置最大工作线程数 (SQL Server Management Studio)
  • 原文地址:https://www.cnblogs.com/rixiang/p/5249560.html
Copyright © 2011-2022 走看看