您的位置:首页 > 其它

用JFreeChart在网页中创建图表

2009-10-15 12:12 169 查看
用JFreeChart来创建一张图片,并将其显示到网页上。

此方法在jsp页面中使用了java代码,实际当中并不这样应用,仅做为了解。

public static void main(String[] args) {

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

//设置title字体

chart.setTitle(new TextTitle("某公司组织结构图", new Font("宋体", Font.BOLD, 22)));

//取出第一个图例,即图表下面的第一个说明

LegendTitle legend = chart.getLegend(0);

legend.setItemFont(new Font("微软雅黑", new Font("宋体", Font.BOLD + Font.ITALIC, 20)));

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

plot.setLabelFont(new Font("隶书", Font.BOLD, 16));

//定义一个文件输出流

OutputStream os = new FileOutputStream("company.jpeg");

//将图表输出到这个文件流中

ChartUtilities.writeChartAsJPEG(os, chart, 1024, 768);

os.close();

}

private static DefaultPieDataset getDataset() {

DefaultPieDataset dpd = new DefaultPieDataset();

dpd.setValue("管理人员", 25);

dpd.setValue("市场人员", 25);

dpd.setValue("开发人员", 45);

dpd.setValue("其他人员", 20);

}

将产生的图表文件显示在jsp文件中,用到了DisplayChart这个类

先要在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>

new一个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.createPieChart3D("某公司组织结构图",dpd, true, false, false);

String fileName = ServletUtilities.saveChartAsPNG(chart,800,600,session);

String url = request.getContextPath() + "/DisplayChart?filename=" + fileName;

%>

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

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: