JfreeChart的使用
一、JFreeChart 项目简介
JFreeChart是开放源代码站点SourceForge.net上的一个JAVA项目,它主要用来各种各样的图表,这些图表包括:饼图、柱状图(普通柱状图以及堆栈柱状图)、线图、区域图、分布图、混合图、甘特图以及一些仪表盘等。JFreeChart可以方便的与Swing相结合使用,还可以导入到Web页面中,更是可以方便的利用其工厂方法将图表写入jpeg或者png格式的图片中
官 网 :http://www.jfree.org/jfreechart/index.html
下载地址 :http://sourceforge.net/projects/jfreechart/files/
API : http://www.jfree.org/jfreechart/api/javadoc/index.html
二、JFreeChart 核心类库介绍:
研究jfreechart源码发现源码的主要由两个大的包组成:org.jfree.chart,org.jfree.data。其中前者主要与图形 本身有关,后者与图形显示的数据有关。核心类主要有:
org.jfree.chart.JFreeChart :图表对象,任何类型的图表的最终表现形式都是在该对象进行一些属性的定制。JFreeChart引擎本身提供了一个工厂类用于创建不同类型的图表对象
org.jfree.data.category.XXXDataSet: 数据集对象,用于提供显示图表所用的数据。根据不同类型的图表对应着很多类型的数据集对象类
org.jfree.chart.plot.XXXPlot :图表区域对象,基本上这个对象决定着什么样式的图表,创建该对象的时候需要Axis、Renderer以及数据集对象的支持
org.jfree.chart.axis.XXXAxis :用于处理图表的两个轴:纵轴和横轴
org.jfree.chart.render.XXXRender :负责如何显示一个图表对象
org.jfree.chart.urls.XXXURLGenerator: 用于生成Web图表中每个项目的鼠标点击链接
XXXXXToolTipGenerator: 用于生成图象的帮助提示,不同类型图表对应不同类型的工具提示类
三、建立jfreechart的主要步骤
要建立一个JFreeChart图形主要有以下个步骤(以柱图为例):
第一步:建立DataSet数据源
第二步:创造JFreeChart
第三步:设置图形显示的属性
第四步:写入图片或输出界面利用
四、开发例子
4.1直接生成图片
PieChartPicture.java
import java.awt.Color;
import java.awt.Font;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
public class PieChartPicture {
public static void main(String[] args) {
PieDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createPieChart3D(" 项目进度分布", // chart title
dataset,// data
true,// include legend
true, false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
// 图片中显示百分比:默认方式
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})", NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
// 设置背景色为白色
chart.setBackgroundPaint(Color.white);
// 指定图片的透明度(0.0-1.0)
plot.setForegroundAlpha(1.0f);
// 指定显示的饼图上圆形(false)还椭圆形(true)
plot.setCircular(true);
// 设置图标题的字体
Font font = new Font("宋体", Font.CENTER_BASELINE, 20);
TextTitle title = new TextTitle(" 项目状态分布");
title.setFont(font);
chart.setTitle(title);
//设置图中图例的字体
plot.setLabelFont(new Font("宋体", Font.PLAIN, 12));
// 设置图下面图例的字体
LegendTitle legend = chart.getLegend();
legend.setItemFont(new Font("宋体", Font.BOLD, 14));
FileOutputStream fos_jpg = null;
try {
fos_jpg = new FileOutputStream("D:\\项目状态分布.jpg");
ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f, chart, 640, 480,null);
fos_jpg.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static PieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("市场前期", new Double(10));
dataset.setValue("立项", new Double(15));
dataset.setValue("计划", new Double(10));
dataset.setValue("需求与设计", new Double(10));
dataset.setValue("执行控制", new Double(35));
dataset.setValue("收尾", new Double(10));
dataset.setValue("运维", new Double(10));
return dataset;
}
}
4.2 ApplicationFrame 方式
import java.awt.Color;
import java.awt.Font;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.title.LegendTitle;
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 PieChartDemo_ApplicationFrame extends ApplicationFrame {
public PieChartDemo_ApplicationFrame(String title) {
super(title);
setContentPane(createDemoPanel());
}
private static JFreeChart createChart(PieDataset dataset) {
JFreeChart chart = ChartFactory.createPieChart3D( " 项目进度分布", // chart title
dataset,// data
true,// include legend
true, false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
// 图片中显示百分比:默认方式
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})", NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
// 设置背景色为白色
chart.setBackgroundPaint(Color.white);
// 指定图片的透明度(0.0-1.0)
plot.setForegroundAlpha(1.0f);
// 指定显示的饼图上圆形(false)还椭圆形(true)
plot.setCircular(true);
// 设置图标题的字体
Font font = new Font("宋体", Font.CENTER_BASELINE, 20);
TextTitle title = new TextTitle(" 项目状态分布");
title.setFont(font);
chart.setTitle(title);
//设置图中图例的字体
plot.setLabelFont(new Font("宋体", Font.PLAIN, 12));
// 设置图下面图例的字体
LegendTitle legend = chart.getLegend();
legend.setItemFont(new Font("宋体", Font.BOLD, 14));
return chart;
}
public static JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());
return new ChartPanel(chart);
}
private static PieDataset createDataset() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("市场前期", new Double(10));
dataset.setValue("立项", new Double(15));
dataset.setValue("计划", new Double(10));
dataset.setValue("需求与设计", new Double(10));
dataset.setValue("执行控制", new Double(35));
dataset.setValue("收尾", new Double(10));
dataset.setValue("运维", new Double(10));
return dataset;
}
public static void main(String[] args) {
PieChartDemo_ApplicationFrame demo = new PieChartDemo_ApplicationFrame("Pie Chart Demo 1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
4.3 jsp+servlet+javabean方式
jsp页面,调用javabean的方法生成chart,并将 chart以BufferedImage形式写入session。session.setAttribute("chartImage", chartImage);
在servlet中获得chart, BufferedImage chartImage = (BufferedImage) session.getAttribute("chartImage");设置response.setContentType("image/png");
页面调用servlet显示图片。<img src="http://localhost:8080/jfreechart/servlet/ChartViewer" border=0 >
创建servlet
package com.ncepu;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.keypoint.PngEncoder;
public class ChartViewer extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 从session 中获得chart
HttpSession session = request.getSession();
BufferedImage chartImage = (BufferedImage) session.getAttribute("chartImage");
// 设置 content type so the browser can see this as a picture
response.setContentType("image/png");
// send the picture
PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);
response.getOutputStream().write(encoder.pngEncode());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void destroy() {
}
}
配置servlet
<servlet>
<servlet-name>ChartViewer</servlet-name>
<servlet-class>com.ncepu.ChartViewer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ChartViewer</servlet-name>
<url-pattern>/servlet/ChartViewer</url-pattern>
</servlet-mapping>
javabean中生成chart
package com.ncepu;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
public class Pie3DDemo {
// 生成数据集
private DefaultPieDataset getDataset() {
String[] section = new String[] { "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
double[] data = new double[section.length];
for (int i = 0; i < data.length; i++) {
data[i] = 10 + (Math.random() * 10);
}
DefaultPieDataset dataset = new DefaultPieDataset();
for (int i = 0; i < data.length; i++) {
dataset.setValue(section[i], data[i]);
}
return dataset;
}
public String getChartViewer(HttpServletRequest request,HttpServletResponse response) {
DefaultPieDataset dataset = getDataset();
// 生产chart
JFreeChart chart = ChartFactory.createPieChart3D("Pie3D Chart Demo",dataset, true, true, false);
// 设置背景色
chart.setBackgroundPaint(Color.cyan);
PiePlot plot = (PiePlot) chart.getPlot();
plot.setNoDataMessage("No data available");
plot.setLabelGenerator(null);
ChartRenderingInfo info = null;
HttpSession session = request.getSession();
try {
// Create RenderingInfo object
response.setContentType("text/html");
info = new ChartRenderingInfo(new StandardEntityCollection());
BufferedImage chartImage = chart.createBufferedImage(640, 400, info);
// 将 chart以BufferedImage形式写入session,
session.setAttribute("chartImage", chartImage);
} catch (Exception e) {
}
String pathInfo = "http://";
pathInfo += request.getServerName();
int port = request.getServerPort();
pathInfo += ":" + String.valueOf(port);
pathInfo += request.getContextPath();
String chartViewer = pathInfo + "/servlet/ChartViewer";
return chartViewer;
}
}
页面index.jsp
<html>
<head>
<title>Pie Chart Demo 1</title>
</head>
<jsp:useBean id="myChart" scope="session" class="com.ncepu.Pie3DDemo" />
<body>
<h2>Pie Chart Demo</h2>
<%String chartViewer = myChart.getChartViewer(request, response);%>
<img src="<%=chartViewer%>" border=0 >
<img src="http://localhost:8080/jfreechart/servlet/ChartViewer" border=0 >
</body>
</html>
4.4 web应用中推荐方式---->配置DisplayChart
package jfree; import java.awt.Color; import java.awt.Font; import java.io.IOException; import java.io.PrintWriter; import java.text.NumberFormat; import java.text.SimpleDateFormat; import javax.servlet.http.HttpSession; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.servlet.ServletUtilities; import org.jfree.chart.title.LegendTitle; import org.jfree.chart.title.TextTitle; import org.jfree.data.time.Day; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.ui.RectangleInsets; /** * 曲线图的绘制 */ public class LineXYChart { /** * 返回生成图片的文件名 * * @param session * @param pw * @return 生成图片的文件名 */ public String getLineXYChart(HttpSession session, PrintWriter pw) { XYDataset dataset = this.createDateSet();// 建立数据集 String fileName = null; // 建立JFreeChart JFreeChart chart = ChartFactory.createTimeSeriesChart("JFreeChart时间曲线序列图", // title "Date", // x-axis label "Price", // y-axis label dataset, // data true, // create legend? true, // generate tooltips? false // generate URLs? ); // 设置JFreeChart的显示属性,对图形外部部分进行调整 chart.setBackgroundPaint(Color.red);// 设置曲线图背景色 // 设置字体大小,形状 Font font = new Font("宋体", Font.BOLD, 16); TextTitle title = new TextTitle("JFreeChart时间曲线序列图", font); chart.setTitle(title); // 副标题 TextTitle subtitle = new TextTitle("副标题", new Font("黑体", Font.BOLD, 12)); chart.addSubtitle(subtitle); chart.setTitle(title); // 标题 // 设置图示标题字符 // TimeSeries s1 = new TimeSeries("历史曲线", Day.class);该中文字符 LegendTitle legengTitle = chart.getLegend(); legengTitle.setItemFont(font); XYPlot plot = (XYPlot) chart.getPlot();// 获取图形的画布 plot.setBackgroundPaint(Color.lightGray);// 设置网格背景色 plot.setDomainGridlinePaint(Color.green);// 设置网格竖线(Domain轴)颜色 plot.setRangeGridlinePaint(Color.white);// 设置网格横线颜色 plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));// 设置曲线图与xy轴的距离 plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setShapesVisible(true);// 设置曲线是否显示数据点 } // 设置Y轴 NumberAxis numAxis = (NumberAxis) plot.getRangeAxis(); NumberFormat numFormater = NumberFormat.getNumberInstance(); numFormater.setMinimumFractionDigits(2); numAxis.setNumberFormatOverride(numFormater); // 设置提示信息 StandardXYToolTipGenerator tipGenerator = new StandardXYToolTipGenerator("历史信息{1} 16:00,{2})", new SimpleDateFormat("MM-dd"), numFormater); r.setToolTipGenerator(tipGenerator); // 设置X轴(日期轴) DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MM-dd")); ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); try { fileName = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session);// 生成图片 } catch (IOException e) { e.printStackTrace(); } pw.flush(); return fileName;// 返回生成图片的文件名 } /** * 建立生成图形所需的数据集 * * @return 返回数据集 */ private XYDataset createDateSet() { TimeSeriesCollection dataset = new TimeSeriesCollection();// 时间曲线数据集合 TimeSeries s1 = new TimeSeries("历史曲线", Day.class);// 创建时间数据源,每一个//TimeSeries在图上是一条曲线 // s1.add(new Day(day,month,year),value),添加数据点信息 s1.add(new Day(1, 2, 2006), 123.51); s1.add(new Day(2, 2, 2006), 122.1); s1.add(new Day(3, 2, 2006), 120.86); s1.add(new Day(4, 2, 2006), 122.50); s1.add(new Day(5, 2, 2006), 123.12); s1.add(new Day(6, 2, 2006), 123.9); s1.add(new Day(7, 2, 2006), 124.47); s1.add(new Day(8, 2, 2006), 124.08); s1.add(new Day(9, 2, 2006), 123.55); s1.add(new Day(10, 2, 2006), 122.53); dataset.addSeries(s1); dataset.setDomainIsPointsInTime(true); return dataset; } }
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>
jsp页面
<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.io.PrintWriter"%>
<%@page import="jfree.LineXYChart;"%>
<%
jfree.LineXYChart xyChart = new jfree.LineXYChart();
String fileName = xyChart.getLineXYChart(session, new PrintWriter(out));
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + fileName;
%>
<html>
<head>
<title>JFreeChart使用例子</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<img src="<%=graphURL%>" width=500 height=300 border=0>
</body>
</html>
访问jp页面结果
五、图片热点
plot.setURLGenerator(new StandardPieURLGenerator("PingImage2.jsp","type"));//设定链接
生成图片后 ChartUtilities.writeImageMap(pw, "map0", info,true);
页面 <img src="<%=graphURL%>" width=500 height=300 border=0 usemap="#map0" />
例子代码:
package jfree;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
/**
* 曲线图的绘制
*/
public class PieChart {
/**
* 返回生成图片的文件名
*
* @param session
* @param pw
* @return 生成图片的文件名
*/
public String getPieChart(HttpSession session, PrintWriter pw) {
String fileName = null;
PieDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createPieChart3D(" 项目进度分布", // chart title
dataset,// data
true,// include legend
true, false);
PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setURLGenerator(new StandardPieURLGenerator("tohot.jsp",
"type"));//设定链接
// 图片中显示百分比:默认方式
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})", NumberFormat.getNumberInstance(),new DecimalFormat("0.00%")));
// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
// 设置背景色为白色
chart.setBackgroundPaint(Color.white);
// 指定图片的透明度(0.0-1.0)
plot.setForegroundAlpha(1.0f);
// 指定显示的饼图上圆形(false)还椭圆形(true)
plot.setCircular(true);
// 设置图标题的字体
Font font = new Font("宋体", Font.CENTER_BASELINE, 20);
TextTitle title = new TextTitle(" 项目状态分布");
title.setFont(font);
chart.setTitle(title);
//设置图中图例的字体
plot.setLabelFont(new Font("宋体", Font.PLAIN, 12));
// 设置图下面图例的字体
LegendTitle legend = chart.getLegend();
legend.setItemFont(new Font("宋体", Font.BOLD, 14));
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
try {
fileName = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session);// 生成图片
ChartUtilities.writeImageMap(pw, "map0", info,true);
} catch (IOException e) {
e.printStackTrace();
}
pw.flush();
return fileName;// 返回生成图片的文件名
}
/**
* 建立生成图形所需的数据集
*
* @return 返回数据集
*/
private static PieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("市场前期", new Double(10));
dataset.setValue("立项", new Double(15));
dataset.setValue("计划", new Double(10));
dataset.setValue("需求与设计", new Double(10));
dataset.setValue("执行控制", new Double(35));
dataset.setValue("收尾", new Double(10));
dataset.setValue("运维", new Double(10));
return dataset;
}
}
index.jsp
<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.io.PrintWriter"%>
<%@page import="jfree.PieChart;"%>
<%
jfree.PieChart pieChart = new jfree.PieChart();
String fileName = pieChart.getPieChart(session, new PrintWriter(out));
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + fileName;
%>
<html>
<head>
<title>JFreeChart热点例子</title>
</head>
<body>
<img src="<%=graphURL%>" width=500 height=300 border=0 usemap="#map0" />
</body>
</html>
tohot.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'PingImage.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<%
request.setCharacterEncoding("ISO8859-1") ;
String type = new String(request.getParameter("type").getBytes("ISO_8859_1"), "UTF-8");
%>
选择的类型为: <%=type %>
<br>
</body>
</html>
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>
结果:
点击运行控制结果:
注意:
1、页面上的usemap="#map0"比保存时候ChartUtilities.writeImageMap(pw, "map0", info,true);多一个#号
2、注意乱码问题。 页面都是utf-8编码,而writeImageMap貌似用的ISO_8859_1
request.setCharacterEncoding("ISO8859-1") ;
String type = new String(request.getParameter("type").getBytes("ISO_8859_1"), "UTF-8");
六、乱码问题
1、一种是中文显示为问号(?),这种情况一般是由于汉字编码转换出错。
2、一种是中文显示为方框(□),这种情况一般是由于jfreechart中用到的字体不存在。重新设置字体即可
使用JFreeChart绘制图表的时候,如果使用默认的字体会导致图标中的汉字显示为乱码。解决方法如下:
JFreeChart是用户使用该库提供的各类图标的统一接口,JFreeChart主要由三个部分构成:title(标题),legend(图释),plot(图表主体)。三个部分设置字体的方法分别如下:
1.Title
TextTitle textTitle = freeChart.getTitle();
textTitle.setFont(new Font("宋体",Font.BOLD,20));
2.Legend
LegendTitle legend = freeChart.getLegend();
if (legend != null)
{
legend.setItemFont(new Font("宋体", Font.BOLD, 20));
}
3.Plot
对于不同类型的图表对应Plot的不同的实现类,设置字体的方法也不完全相同。
对于使用CategoryPlot的图表(如柱状图):CategoryPlot plot = (CategoryPlot)freeChart.getPlot();
CategoryAxis domainAxis = plot.getDomainAxis();//(柱状图的x轴)
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴坐标上的字体
domainAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴上的标题的字体
ValueAxis valueAxis = plot.getRangeAxis();//(柱状图的y轴)
valueAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的字体
valueAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的标题的字体
对于使用PiePlot的图标(如饼状图)
PiePlot plot = (PiePlot)freeChart.getPlot();
plot.setLabelFont(new Font("宋体",Font.BOLD,15));