Jfreechart柱状图和饼图

需要用到的包:

jfreechart-1.0.5.jar

jcommon-1.0.9.jar

实现代码:

@Namespace("/Test")
public class Test extends ActionSupport{
	
	@Action(value = "bing")
	public String bing() {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("image/png");

  //饼图
           PieDataset dataset=createPieDataset();
           JFreeChart jfreechart=ChartFactory.createPieChart3D("图书销售比例", dataset,true , true, true);
           //PiePlot plot=(PiePlot) jfreechart.getPlot();
           ChartUtilities.writeChartAsPNG(response.getOutputStream(),jfreechart,400,300);
              //也可以保存到本地硬盘
           ChartUtilities.saveChartAsPNG(new File("e:\\chart.png"), jfreechart, 400, 300);}
	
	@Action(value ="bar")
	public String bar() {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("image/png");

		//柱状图
           CategoryDataset categorydataset=createCategoryDataset();
           JFreeChart jfreechart2=ChartFactory.createBarChart3D("08年水果销售量", "按季度", "销量", categorydataset, PlotOrientation.VERTICAL, true, true, false);  
           CategoryPlot catplot=(CategoryPlot) jfreechart2.getPlot();
       
           ChartUtilities.writeChartAsPNG(response.getOutputStream(),jfreechart2,400,300);	}
public PieDataset createPieDataset(){
  Random random=new Random();
  DefaultPieDataset dataset=new DefaultPieDataset();
  dataset.setValue("计算机", random.nextInt(100));
  dataset.setValue("英语", random.nextInt(100));
  dataset.setValue("数学", random.nextInt(100));
  return dataset;
  
 }
 
 public CategoryDataset createCategoryDataset(){
  Random random=new Random();
  String [] category1={"第一季度","第二季度","第三季度","第四季度"};
  String [] category2={"苹果","荔枝","葡萄"};
  DefaultCategoryDataset defaultdataset=new DefaultCategoryDataset();
  for(int i=0;i<category1.length;i++){
   String cat1=category1[i];
   for(int j=0;j<category2.length;j++){
    String cat2=category2[j]; 
    defaultdataset.addValue(random.nextInt(100),cat2,cat1);
   }
  }
  return defaultdataset;
 }	

}

 显示可以直接在界面输入它的action地址显示,也可以把它固定在jsp页面通过img标签显示:

<script src="<%=request.getContextPath()%>/js/jquery-1.6.2.min.js" type="text/javascript"></script>
		
	<script language="javascript">
	
    $(document).ready(function() {

	$("#se").change(function(){
	    var  chart = $("#se").val();
		
		if(chart == "1"){
			$("#zz").hide();
			$("#bb").show();
		}
		if(chart == "2"){
			$("#bb").hide();
			$("#zz").show();
		}
		if(chart ==""){
		    $("#bb").hide();
			$("#zz").hide();
		}
	  });
	
    });
	
	</script>
  </head>
  
  <body>
  
     <select  id="se">
          <option  value=""></option>
          <option  value="1">饼图
          <option  value="2">柱状图
     </select>

    <div style="display: none" id="bb">
    <img src="<%=basePath%>/Test/bing.action"/>
    </div>
    
    <div style="display: none" id="zz">
    <img src="<%=basePath%>/Test/bar.action"/>
    </div>
  </body>

 

你可能感兴趣的:(jfreechart)