JFreeChart中的饼形图

在Servlet中的代码:

package com.lyb.pic;

import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class Pie extends HttpServlet {


private static final long serialVersionUID =-8595833690404444349L;
public void doGet(HttpServletRequestrequest,HttpServletResponse response) throws IOException {
  doPost(request,response);
}
public void doPost(HttpServletRequestrequest,HttpServletResponse response) throws IOException {
  //设置返回样式
  response.setContentType("image/png");
  response.setCharacterEncoding("utf-8");
  //获取数据集
  PieDataset pie =createPieDataset();
  //创建图形界面
  JFreeChart jfc =ChartFactory.createPieChart3D("我的书籍组成", pie, true, true,false);
  //设置标题的字体,为了防止中文乱码
  TextTitle tt = newTextTitle("我的书籍组成");
  tt.setFont(new Font("宋体",Font.BOLD, 15));
  jfc.setTitle(tt);
   //设置图例的字体,为了防止中文乱码
  jfc.getLegend().setItemFont(newFont("宋体", Font.BOLD, 15));
  //获得图表区域对象
  PiePlot plot =(PiePlot)jfc.getPlot();
  //设置图表区域分类标签字体大小,为了防止中文乱码
  plot.setLabelFont(newFont("宋体", Font.BOLD, 12));
  //设置分类标签字体的颜色
  Paint paint = newColor(24,127,220);
  plot.setLabelPaint(paint);
  //设置图表区域无数据时的默认值
  plot.setNoDataMessage("没有此书籍");
  //指定显示的饼图上圆形(false)还椭圆形(true)
  plot.setCircular(false);
  //设置图表区域文字与图表区域之间的间隔,0.05表示5%
  plot.setLabelGap(0.05);
  //将图表以数据流的方式返回给
  ChartUtilities.writeChartAsPNG(response.getOutputStream(),jfc, 800, 500);
}
public static PieDataset createPieDataset(){
  //创建饼型图所需数据
  DefaultPieDataset dpd = newDefaultPieDataset();
  dpd.setValue("java",DataUtils.getNumber());
  dpd.setValue("c++",DataUtils.getNumber());
  dpd.setValue("php",DataUtils.getNumber());
  dpd.setValue("动画",DataUtils.getNumber()); 
  return dpd;
}
}

生成的假数据代码:

package com.lyb.pic;

import java.util.Random;

public class DataUtils {

private static Random random = newRandom();
private static final int NUMBER = 100;
public static int getNumber() {
  returnrandom.nextInt(NUMBER);
}
}



xml中的代码:
<servlet>

<servlet-name>pie</servlet-name>
  <servlet-class>com.lovo.lyb.Pie</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>pie</servlet-name>
   <url-pattern>/pie</url-pattern>
</servlet-mapping>

你可能感兴趣的:(java)