首先是填写数据和生成图像的Java类(可以根据实际情况用在action里):
import java.awt.Color;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
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.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.util.Rotation;
public class CreateChart {
/**
*
*/
private static final long serialVersionUID = 1L;
private static CategoryDataset createDataset() {
String s = "First";
String s3 = "Category 1";
String s4 = "Category 2";
String s5 = "Category 3";
String s6 = "Category 4";
String s7 = "Category 5";
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
defaultcategorydataset.addValue(80D, s, s3);
defaultcategorydataset.addValue(40D, s, s4);
defaultcategorydataset.addValue(30D, s, s5);
defaultcategorydataset.addValue(50D, s, s6);
defaultcategorydataset.addValue(90D, s, s7);
return defaultcategorydataset;
}
private static JFreeChart createChart(CategoryDataset categorydataset) {
SpiderWebPlot spiderwebplot = new SkillScorePlot(categorydataset);
spiderwebplot.setStartAngle(45D);
categorydataset.getValue(0, 1);
spiderwebplot.setBackgroundPaint(Color.LIGHT_GRAY);
spiderwebplot.setMaxValue(100D);
spiderwebplot.setDirection(Rotation.ANTICLOCKWISE);
spiderwebplot.setAxisLinePaint(Color.blue);
spiderwebplot.setInteriorGap(0.3D);
spiderwebplot.setToolTipGenerator(new StandardCategoryToolTipGenerator());
JFreeChart jfreechart = new JFreeChart("Competency Overall",TextTitle.DEFAULT_FONT, spiderwebplot, false);
jfreechart.setBackgroundPaint(Color.cyan);
return jfreechart;
}
public String getSpiderChart(HttpSession session, PrintWriter printWriter){
JFreeChart jfreeChart = createChart(createDataset());
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String fileName = null;
try {
fileName = ServletUtilities.saveChartAsPNG(jfreeChart, 500, 300, info,
session);// 生成图片
// Write the image map to the PrintWriter
ChartUtilities.writeImageMap(printWriter, fileName, info, false);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
return fileName;// 返回生成图片的文件名
}
}
因为要用到显示数据的标签,必须重写SpiderWebPlot类的drawLabel方法:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextAttribute;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.data.category.CategoryDataset;
/**
*
* @author Vincent.zheng this class is for draw the label.
*
*/
public class SkillScorePlot extends SpiderWebPlot {
private static final long serialVersionUID = 1L;
/**
* @param LABELANDAXISGAP : the gap between the label and the axis.
* @param LABELANDCENTERGAP : the gap between the label and the center point.
*/
private static final double LABELANDAXISGAP = 10;
private static final double LABELANDCENTERGAP = 1;
public SkillScorePlot(CategoryDataset categorydataset) {
super(categorydataset);
}
/**
* @param extent : the angle gap between two near axis.
*/
@Override
protected void drawLabel(Graphics2D graphics2D, Rectangle2D rectangle2D,
double value, int cat, double startAngle, double extent) {
super
.drawLabel(graphics2D, rectangle2D, value, cat, startAngle,
extent);
/**
* @param sumAxisNum : the sum number of the axis.
* @param centerX : the center X coordinate of the panel.
* @param centerY : the center Y coordinate of the panel.
*/
int sumAxisNum = this.getDataset().getColumnCount();
double centerX = rectangle2D.getCenterX();
double centerY = rectangle2D.getCenterY();
Arc2D arc2D;
FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
for (int currentAxisNum = 0; currentAxisNum < sumAxisNum; currentAxisNum++) {
/**
* @param currentValue : the value of the current axis.
* @param label : the value on the label.
* @param scale : the scale of the point value to the max value on
* current axis.
*/
double currentValue = this.getDataset().getValue(0, currentAxisNum).doubleValue();
String label = String.valueOf((int) currentValue);
double scale = (currentValue / this.getMaxValue());
/**
* the coordinate of the label
*/
if (startAngle == this.getStartAngle()) {
double labelX;
double labelY;
/**
* @param currentAngle : the angle of the current axis where the label place.
*/
double currentAngle = extent * currentAxisNum + startAngle;
arc2D = new Arc2D.Double(rectangle2D, currentAngle, 0, Arc2D.OPEN);
Point2D point2D = arc2D.getEndPoint();
double axisX = Math.abs(point2D.getX() - centerX)* scale;
double axisY = Math.abs(point2D.getY() - centerY)* scale;
if (currentAngle >= 0 && currentAngle < 90) {
labelX = centerX + axisX;
labelY = centerY - axisY;
} else if (currentAngle < 180) {
labelX = centerX - axisX;
labelY = centerY - axisY;
} else if (currentAngle < 270) {
labelX = centerX - axisX;
labelY = centerY + axisY;
} else {
labelX = centerX + axisX;
labelY = centerY + axisY;
}
LineMetrics lm = getLabelFont().getLineMetrics(label,
fontRenderContext);
double ascent = lm.getAscent();
/**
* set the gap between the label and axis, or between the label
* and the center point.
*/
if (Math.abs(labelX - rectangle2D.getCenterX()) < LABELANDCENTERGAP) {
labelX += LABELANDAXISGAP;
labelY += ascent / (float) 2;
} else if (Math.abs(labelY - rectangle2D.getCenterY()) < LABELANDCENTERGAP) {
labelY += LABELANDAXISGAP;
} else if (labelX >= rectangle2D.getCenterX()) {
if (labelY < rectangle2D.getCenterY()) {
labelX += LABELANDAXISGAP;
labelY += LABELANDAXISGAP;
} else {
labelX -= LABELANDAXISGAP;
labelY += LABELANDAXISGAP;
}
} else {
if (labelY > rectangle2D.getCenterY()) {
labelX -= LABELANDAXISGAP;
labelY -= LABELANDAXISGAP;
} else {
labelX += LABELANDAXISGAP;
labelY -= LABELANDAXISGAP;
}
}
//set label font
HashMap<TextAttribute, Comparable<?>> hm = new HashMap<TextAttribute, Comparable<?>>();
hm.put(TextAttribute.SIZE, 14);
hm.put(TextAttribute.FAMILY,"Impact");//
Font font = new Font(hm);
graphics2D.setPaint(Color.blue);
graphics2D.setFont(font);
graphics2D.drawString(label, (float) labelX, (float) labelY);
}
}
}
}
以上java代码就完成了,页面也很简单:
<%@ page contentType="text/html;charset=gb2312" pageEncoding="GB2312"%>
<%@ page import="com.bleum.test.ok.*"%>
<%@ page import="java.io.PrintWriter"%>
<%
CreateChart createChart = new CreateChart();
String fileName = createChart.getSpiderChart(session,
new PrintWriter(out));
String graphURL = request.getContextPath()
+ "/servlet/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
usemap="<%=fileName%>">
</body>
</html>
不过要注意这里的servlet是JFreeChart已经封装好的一个类:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>test222</display-name>
<welcome-file-list>
<welcome-file>mychart.jsp</welcome-file>
</welcome-file-list>
<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>/servlet/DisplayChart</url-pattern>
</servlet-mapping>
</web-app>