JFreeChart的使用(web中照片,jmf,spring)

2024-05-27 08:18

本文主要是介绍JFreeChart的使用(web中照片,jmf,spring),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前提:导入需要的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中加入以下配置信息.

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

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;}@Overridepublic 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的使用(web中照片,jmf,spring)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1006931

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp