JFreeChart 内置JDBC的使用示例

1.程序结构:

JFreeChart 内置JDBC的使用示例

2.ChartUtil.java代码清单:

package com.xqh.util.jfree;
 
import java.awt.Font;
import java.awt.Image;
import java.io.IOException;
import java.sql.SQLException;
import java.text.NumberFormat;
 
import javax.imageio.ImageIO;
 
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.PieDataset;
import org.jfree.data.jdbc.JDBCPieDataset;
import org.jfree.ui.VerticalAlignment;
 
/**
 * 
 * @author Snway
 * 
 */
public class ChartUtil {
    /**
     * 查询数据库并初始化数据集合
     * 
     * @return PieDataset对象
     */
    public static PieDataset initPieData() {
        String driverName = "com.mysql.jdbc.Driver"; // 数据库驱动
        String url = "jdbc:mysql://localhost:3306/java_db"; // 数据库连接URL
        String user = "root"; // 数据库用户名
        String psd = "1120"; // 数据库密码
        JDBCPieDataset dataset = null;// 数据集合
        try {
            dataset = new JDBCPieDataset(url, driverName, user, psd); // 通过JDBC创建数据集合
            String query = "select category, value from tb_shop"; // SQL语句
            dataset.executeQuery(query); // 查询并向数据集合中添加数据
            dataset.close(); // 关闭数据库连接
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return dataset;
    }
 
    /**
     * 创建饼形图例对象
     * 
     * @return chart
     */
    public static JFreeChart createChart() {
        // 通过ChartFactory创建JFreeChart
        JFreeChart chart = ChartFactory.createPieChart3D("XX商场月销量统计", // 图表标题
                initPieData(),// 数据集合
                true,// 是否显示图例标识
                false,// 是否显示tooltips
                false);// 是否支持超链接
        chart.getTitle().setFont(new Font("隶书", Font.BOLD, 25)); // 设置标题字体
        chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15)); // 设置图例类别字体
 
        PiePlot plot = (PiePlot) chart.getPlot(); // 获取绘图区对象
        plot.setForegroundAlpha(0.5F);// 设置绘图区前景色透明度
        plot.setLabelFont(new Font("宋体", Font.PLAIN, 12)); // 设置分类标签的字体
        plot.setCircular(true);// 设置饼形为正圆
        // 设置分类标签的格式
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat
                        .getPercentInstance()));
        return chart;
    }
 
    // 本地测试
    public static void main(String[] args) {
        ChartFrame cf = new ChartFrame("Test", createChart());
        cf.pack();
        cf.setVisible(true);
    }
}
3.index.jsp代码清单:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="org.jfree.chart.servlet.ServletUtilities, 
                            com.xqh.util.jfree.ChartUtil" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Java 图书销量统计</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <%
        String fileName = ServletUtilities.saveChartAsJPEG(ChartUtil.createChart(), 450, 300, session);
        String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + fileName;
    %>
    <img src="<%=graphURL %>" border="1"/>
  </body>
</html>

4.web.xml配置信息:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.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>
5.运行结果:

JFreeChart 内置JDBC的使用示例