当前位置: 首页 > 工具软件 > JChart2D > 使用案例 >

JChart用法(制作饼图,柱图)

轩辕庆
2023-12-01

JSP文件:

<html>
<meta http-equiv="refresh" content="5">
<script language="javascript">
 function doUrl()
 {
  var temp = document.form1.choice.value;
  
  if(temp =='pie')
  {
   window.location.href='row2.jsp?type=pie';
  }
  else
  {
   window.location.href='row2.jsp';
  }
 }
</script> 
<%
 String temp = ((request.getParameter("type")==null)?"post":request.getParameter("type"));
%>
<body>
<form action="row2.jsp" name="form1">
 <a href="chart?type=pie">饼图</a>
 <a href="chart">柱型图</a>

  <select name="choice" οnchange="javascript:doUrl();">
  <%
   if(temp.equals("pie"))
   {
    out.println("<option value='pie' selected>饼图</option>");
    out.println("<option value='row'>柱状图</option>");
   }
   
   else
   {
    
    out.println("<option value='pie'>饼图</option>");
    out.println("<option value='row' selected>柱状图</option>");
   }
  %>
  </select>
  <!--
  <hidden name=choice value=<%=temp%>/>
  -->
  <hidden name="type" value=<%=temp%>/>
</form>
<%
 //String temp = ((request.getParameter("type")==null)?"post":request.getParameter("type"));
 //out.println("-----"+temp+"<br>");

 if(temp.equals("pie"))
 {
%>
  <img src="chart?type=pie">

<%
 }else{ 
%>
  <img src="chart">
<%
}
%>
</body>
</html>

----------------------------java servlet文件(servletChat.java)-------------------------------

package JFreeChart;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.renderer.BarRenderer;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.*;
import org.jfree.chart.axis.*;
import org.jfree.data.DefaultCategoryDataset;
import java.awt.*;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieItemLabelGenerator;
import java.util.*;

import org.jfree.data.DefaultPieDataset;

public class servletChat extends HttpServlet {

 
//  public static threadService thread = new threadService();
  
  public void init(ServletConfig config) throws ServletException {
//   try{ 
//    if(!thread.isAlive())
//    {
//     thread.setSleepTime(60*1000*10);
//     thread.start();
//    }
//   }catch(Exception e)
//   {
//    e.printStackTrace(); 
//   }   
  }
  
  
  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
   res.setContentType("image/jpeg");
   
   
   String type = (req.getParameter("type")==null)?"":req.getParameter("type");
   
   
   
   System.out.println("----------------servletChart--------------------"+type+"   ========");
   
   //pie图表
   if(type.equals("pie"))
   {
    
    
//    org.jfree.data.DefaultPieDataset data = new org.jfree.data.DefaultPieDataset();
    DefaultPieDataset data = new DefaultPieDataset();
    try{
     
     
     
     Hashtable table = DB.getSumCount();
     int number[] = (int[])table.get("sumcount");
     String name[] = (String[])table.get("name");
     
     for(int k=0;k<number.length;k++)
     {
      data.setValue(name[k].trim()+"="+number[k],number[k]); 
     }   
     
     
      
     JFreeChart chart = ChartFactory.createPieChart("招聘网统计图表", // 图表标题
       data, true, // 是否显示图例
       false, false); //写图表对象到文件,参照柱状图生成源码
     
     
     
     
     
          
//     chart.setTitle("招聘网统计表");
     ChartUtilities.writeChartAsJPEG(res.getOutputStream(),chart,400,300);
        
     
        
     System.out.println("chartServlet 饼图finish!!");
     
    }catch(Exception e)
    {
     e.printStackTrace(); 
    }
   }
   
   //row柱图
   else
   {
    try{ 
     DefaultCategoryDataset dataset = new DefaultCategoryDataset();
     
     
     Hashtable table1 = DB.getSumCount();
     int i_temp[] = (int[])table1.get("sumcount");
     String s_temp[] = (String[])table1.get("name");
     
     for(int kk=0;kk<i_temp.length;kk++)
     {
      dataset.addValue(i_temp[kk],s_temp[kk]+"="+i_temp[kk],s_temp[kk]);
     }
     
      
     JFreeChart chart = ChartFactory.createBarChart3D("招聘网统计图表", // 图表标题
      "内容", // 目录轴的显示标签
      "人数", // 数值轴的显示标签
      dataset, // 数据集
      PlotOrientation.VERTICAL, // 图表方向:水平、垂直
      true, // 是否显示图例(对于简单的柱状图必须是false)
      false, // 是否生成工具
      false // 是否生成URL链接
      ); 
     
     
     
     
//     chart.setBackgroundPaint(new Color(0xBBBBDD));
     
     
     CategoryPlot plot = chart.getCategoryPlot();
     CategoryAxis domainAxis = plot.getDomainAxis();
     plot.setDomainAxis(domainAxis);
     ValueAxis rangeAxis = plot.getRangeAxis();
     
     
     BarRenderer renderer = (BarRenderer)plot.getRenderer();
     renderer.setItemMargin(0.1);
     renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
     renderer.setItemLabelsVisible(true);
     plot.setRenderer(renderer);
     
     
//     CategoryPlot plot = chart.getCategoryPlot();
//     
//     NumberAxis axis = (NumberAxis)plot.getRangeAxis();
//     axis.setStandardTickUnits(axis.createIntegerTickUnits());
//     
//     BarRenderer render = (BarRenderer)plot.getRenderer();
//     render.setDrawBarOutline(false);
//     
//     CategoryAxis ca = plot.getDomainAxis();
//     ca.setLowerMargin(0.02);
//     ca.setCategoryMargin(0.10);
//     ca.setUpperMargin(0.02);
     
     
     chart.setTitle("招聘网统计表"); 
     ChartUtilities.writeChartAsJPEG(res.getOutputStream(),chart,400,300);
         
     System.out.println("chartServlet 柱型图表 finish!!");
//     fos_jpg.close();  
    }catch(Exception e)
    {
     e.printStackTrace(); 
    }
   }  
  }
  
  public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
   doGet(req, res); 
  }
 
//  private JFreeChart getChart() {
//   DefaultCategoryDataset dataset = new DefaultCategoryDataset();
//   
// 
//   JFreeChart chart = ChartFactory.createBarChart3D("水果产量图", // 图表标题
//     "水果", // 目录轴的显示标签
//     "产量", // 数值轴的显示标签
//     dataset, // 数据集
//     PlotOrientation.VERTICAL, // 图表方向:水平、垂直
//     true, // 是否显示图例(对于简单的柱状图必须是false)
//     false, // 是否生成工具
//     false // 是否生成URL链接
//     );
   chart.setBackgroundPaint(java.awt.Color.white);
   // 可选,设置图片背景色
   chart.setTitle("www.SenTom.net 网站访问统计表");
   //  可选,设置图片标题
//   return chart;
// 
//  }
//  private static org.jfree.data.DefaultPieDataset getDataSet() {
//   org.jfree.data.DefaultPieDataset dataset = new org.jfree.data.DefaultPieDataset();
//   
//   return dataset;
//  }
}

--------------------------DB.java文件---------------------------------------

package JFreeChart;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;

public class DB
{
 private  static Connection conn = null;
 private  static String url = "jdbc:oracle:thin:@10.1.2.103:1521:webtest";
 private  static String driver = "oracle.jdbc.driver.OracleDriver";
 
 public static Hashtable table = new Hashtable();
 
 public static Connection getConnection()
 {
  try{
   Class.forName(driver);
   conn = DriverManager.getConnection(url,"wsbs","wsbs");
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  return conn;
 }
 
 public static void main(String args[]) throws SQLException
 {
  
  Connection conn = DB.getConnection();
  
  Statement stmt = conn.createStatement();
  ResultSet rs = null;
  
  rs = stmt.executeQuery("select name,number1,number2,sumcount from star008");
  
//  while(rs.next())
//  {
//   System.out.print(rs.getString("NAME")+"/t");
//   System.out.print(rs.getString("NUMBER1")+"/t");
//   System.out.print(rs.getString("NUMBER2")+"/t");
//   System.out.println(rs.getString("SUMCOUNT"));
//  }
  
  Hashtable t1 = getSumCount();
  
  int []int1 = (int[])t1.get("sumcount");
  String []str1 = (String[])t1.get("name");
  
  System.out.println("-----------------------------------");
  for(int ii=0;ii<int1.length;ii++)
  {
//   System.out.print(int1[ii]+"/t");
//   System.out.println(str1[ii]);
  }
  
 }
 
 public static Hashtable getSumCount() throws SQLException
 {
  Connection conn = getConnection();
  Statement stmt = conn.createStatement();
  ResultSet rs = null;
  ResultSet rs1 = null;
  
  rs1 = stmt.executeQuery("select count(*) sum1 from star008");
  int countRecord = 0;
  if(rs1.next())
  {
   countRecord = rs1.getInt("sum1");
  }
  
  rs = stmt.executeQuery("select name,number1,number2,sumcount from star008");
  
  ResultSetMetaData rsmd = rs.getMetaData();
  
  System.out.println(rsmd.getColumnCount());
  
  for(int w=1;w<rsmd.getColumnCount()+1;w++)
  {
   System.out.println(rsmd.getColumnName(w)+"/t/t"+rsmd.getColumnType(w)+"/t/t"+
    rsmd.getColumnTypeName(w)+"/t/t"+rsmd.getColumnClassName(w)+
    rsmd.getCatalogName(w)); 
  }
  
  int [] array = new int[countRecord];
  String [] stringArray = new String[countRecord];
  //table = new Hashtable();
  
  System.out.println(table.containsKey("name")+"/t"+table.containsKey("sumcount"));
  
//  if(!table.containsKey("name") && !table.containsKey("sumcount")) 
//  {
//   System.out.println("从数据库中得到!!!!!!!");
   int temp = 0;
   while(rs.next())
   {
    
    
 //   System.out.print(rs.getString("NAME")+"/t");
 //   System.out.print(rs.getString("NUMBER1")+"/t");
 //   System.out.print(rs.getString("NUMBER2")+"/t");
 //   System.out.println(rs.getInt("SUMCOUNT"));
    
    stringArray[temp] = rs.getString("NAME");
    array[temp] = rs.getInt("SUMCOUNT");
    temp++;
    
   }
   table.put("name",stringArray);
   table.put("sumcount",array);
//  }
//  else
//  {
//   System.out.println("缓存中得到!!!!!"); 
//  }
   
  rs1.close();
  rs.close();
  stmt.close();
  return table;
 }
 
 
}

----------------------------配置web.xml文件------------------------

<servlet>
        <servlet-name>chartServlet</servlet-name>
        <servlet-class>JFreeChart.servletChat</servlet-class>
        <load-on-startup>0</load-on-startup>
</servlet> 
 <servlet-mapping>
        <servlet-name>chartServlet</servlet-name>
        <url-pattern>/chart</url-pattern>
</servlet-mapping>

 

 类似资料: