jfreechart火速应用

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

public class ChartServlet extends HttpServlet
{


 public void doPost( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {
  
//这里先得到一个vote的对象实例
   Vote vote=getvote();

  
  // 得到JFreeChart对象的实例
  JFreeChart chart = getChart( vote );

  // 设置输出对象的类型
  response.setContentType( "image/jpeg" );

  // 输出图形
  ChartUtilities.writeChartAsJPEG( response.getOutputStream(),
   100, chart, 400, 300, null);
 }
 
 
 public void doGet( HttpServletRequest request, HttpServletResponse response )
   throws ServletException, IOException
 {
  doPost( request, response );
 }

// 得到JFreeChart对象的实例
 public static JFreeChart getChart( Vote vote )
 {
  JFreeChart chart = null;

  // 判断是否为饼图
  if( .... )
  {
   // 组织生成饼图的数据
   DefaultPieDataset data = new DefaultPieDataset();
   
   Iterator it = vote.getVoteitems().iterator();

//遍历数据集
   while( it.hasNext() )
   {
    VoteItem vi = (VoteItem)it.next();
//设置要显示图形每一项的标题,具体数字(这里是投票数vi.getvotenum了)
    data.setValue( vi.getTitle(), vi.getVotenum() );
   }
   
   // 判断是否为普通饼图
   if( ..... )
   {
    chart = ChartFactory.createPieChart( vote.getTitle(),
      data, false, false, false );
   }
   else // 3D饼图
   {
    chart = ChartFactory.createPieChart3D( vote.getTitle(),
      data, false, false, false );
   }
  }
  else
  {
   // 组织柱状图的数据
   DefaultCategoryDataset data = new DefaultCategoryDataset();
   
   Iterator it = vote.getVoteitems().iterator();
   while( it.hasNext() )
   {
    VoteItem vi = (VoteItem)it.next();
    data.addValue( vi.getVotenum(), "选项", vi.getTitle() );
   }

   // 判断是否为普通柱状图
   if( .... )
   {
    chart = ChartFactory.createBarChart( vote.getTitle(),
     "选项", "数量", data, PlotOrientation.VERTICAL,
     false, false, false );
   }
   else // 3D柱状图
   {
    chart = ChartFactory.createBarChart3D( vote.getTitle(),
      "选项", "数量", data, PlotOrientation.VERTICAL,
      false, false, false );
   }
  }
  return chart;
 }
}

你可能感兴趣的:(jfreechart)