JFreeChart入门

JFreeChart主要用来各种各样的图表,这些图表包括:饼图、柱状图(普通柱状图以及堆栈柱状图)、线图、区域图、分布图、混合图、甘特图以及一些仪表盘等等

(源代码下载)

示例程序运用的jar包:

  • jcommon-1.0.17.jar
  • jfreechart-1.0.14.jar

1:普通柱状图

这是程序调用CategoryDataset dataset = getDataSet2(); 后所生产的图片

BarChartDemo.java柱状图代码

/** 
* 该类用于演示最简单的柱状图生成
* @author Winter Lau 
*/ 
public class BarChartDemo { 
    public static void main(String[] args) throws IOException{ 
        
        CategoryDataset dataset = getDataSet2(); 
        JFreeChart chart = ChartFactory.createBarChart3D( 
                           "水果产量图", // 图表标题
                           "水果", // 目录轴的显示标签
                           "产量", // 数值轴的显示标签
                            dataset, // 数据集
                            PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                            true,  // 是否显示图例(对于简单的柱状图必须是 false)
                            false, // 是否生成工具
                            false  // 是否生成 URL 链接
                            ); 
        //中文乱码
        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();  
        CategoryAxis domainAxis = categoryplot.getDomainAxis();  
        TextTitle textTitle = chart.getTitle();
        textTitle.setFont(new Font("黑体", Font.PLAIN, 20));      
        domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));  
        domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));  
        numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));  
        numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));  
        chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
                           
        FileOutputStream fos_jpg = null; 
        try { 
            fos_jpg = new FileOutputStream("D:\\BarChart.jpg"); 
            ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f,chart,400,300,null); 
        } finally { 
            try { 
                fos_jpg.close(); 
            } catch (Exception e) {} 
        } 
    } 
    /** 
    * 获取一个演示用的简单数据集对象
    * @return 
    */ 
    private static CategoryDataset getDataSet() { 
        DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
        dataset.addValue(100, "", "苹果"); 
        dataset.addValue(200, "", "梨子"); 
        dataset.addValue(300, "", "葡萄"); 
        dataset.addValue(400, "", "香蕉"); 
        dataset.addValue(500, "", "荔枝"); 
        return dataset; 
    } 
    /** 
    * 获取一个演示用的组合数据集对象
    * @return 
    */ 
    private static CategoryDataset getDataSet2() { 
        DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
        dataset.addValue(100, "北京", "苹果"); 
        dataset.addValue(100, "上海", "苹果"); 
        dataset.addValue(100, "广州", "苹果"); 
        dataset.addValue(200, "北京", "梨子"); 
        dataset.addValue(200, "上海", "梨子"); 
        dataset.addValue(200, "广州", "梨子"); 
        dataset.addValue(300, "北京", "葡萄"); 
        dataset.addValue(300, "上海", "葡萄"); 
        dataset.addValue(300, "广州", "葡萄"); 
        dataset.addValue(400, "北京", "香蕉"); 
        dataset.addValue(400, "上海", "香蕉"); 
        dataset.addValue(400, "广州", "香蕉"); 
        dataset.addValue(500, "北京", "荔枝"); 
        dataset.addValue(500, "上海", "荔枝"); 
        dataset.addValue(500, "广州", "荔枝"); 
        return dataset; 
    } 
} 

2:饼状图

PieChartDemo.java饼状图源代码

/**
 * 用于演示饼图的生成
 */
public class PieChartDemo {
    public static void main(String[] args) throws IOException {
        DefaultPieDataset data = getDataSet();
        JFreeChart chart = ChartFactory.createPieChart3D("水果产量图", // 图表标题
                data, // 数据集
                true, // 是否显示图例(对于简单的柱状图必须是 false)
                false, // 是否生成工具
                false // 是否生成 URL 链接
                );

        //中文乱码
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setLabelFont(new Font("黑体", Font.PLAIN, 20));
        TextTitle textTitle = chart.getTitle();
        textTitle.setFont(new Font("黑体", Font.PLAIN, 20));
        chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));

        // 写图表对象到文件,参照柱状图生成源码
        FileOutputStream fos_jpg = null;
        try {
            fos_jpg = new FileOutputStream("D:\\Pie3DChart.jpg");
            ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f, chart, 400, 300,
                    null);
        } finally {
            try {
                fos_jpg.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取一个演示用的简单数据集对象
     * 
     * @return
     */
    private static DefaultPieDataset getDataSet() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("苹果", 100);
        dataset.setValue("梨子", 200);
        dataset.setValue("葡萄", 300);
        dataset.setValue("香蕉", 400);
        dataset.setValue("荔枝", 500);
        return dataset;
    }
}

其他的图表类型暂时不写了,其实写法也差不多。这里注意两种图形的中文乱码解决方法是不一样的,具体查看源代码中的红色部分

3:将数据库的内容用图形表示出来

index.jsp

<body>
    <form action="servlet/ShowChartServlet" method="get" >
      <input type="submit" value="jfreechart访问数据库生成图表">
    </form>
  </body>

showJfreeChart.jsp

<body>
    <center>
    <img alt="" src="<%=path %>/reports/productSales.jpg">
    </center>
  </body>

ShowChartServlet.java

public class ShowChartServlet extends HttpServlet {

    /**
     * 获取一个演示用的组合数据集对象
     * 
     * @return
     */
    private static CategoryDataset getDataSet() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        // 从数据库中获取
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver"); // 加载驱动程序
            conn = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/shopping?useUnicode=true&amp;characterEncoding=utf8",
                            "root", "root");
            ps = conn.prepareStatement("select p.name, count(pcount) from product p join salesitem si on (p.id = si.productid) group by p.id");
            rs = ps.executeQuery();
            while (rs.next()) {
                dataset.addValue(rs.getInt(2), "", rs.getString(1));
            }
            rs.close();
            rs = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

        return dataset;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        CategoryDataset dataset = getDataSet(); 
        JFreeChart chart = ChartFactory.createBarChart3D( 
                           "产品销量图", // 图表标题
                           "产品", // 目录轴的显示标签
                           "销量", // 数值轴的显示标签
                            dataset, // 数据集
                            PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                            true,  // 是否显示图例(对于简单的柱状图必须是 false)
                            false, // 是否生成工具
                            false  // 是否生成 URL 链接
                            ); 
        //中文乱码
        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();  
        CategoryAxis domainAxis = categoryplot.getDomainAxis();  
        TextTitle textTitle = chart.getTitle();
        textTitle.setFont(new Font("黑体", Font.PLAIN, 20));      
        domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));  
        domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));  
        numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));  
        numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));  
        chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
                           
        FileOutputStream fos_jpg = null; 
        try { 
            fos_jpg = new FileOutputStream("E:\\Workspaces\\MyEclipse 9\\WebProjects\\JFreeChart\\WebRoot\\reports\\productSales.jpg"); 
            ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f,chart,400,300,null); 
             String path = this.getServletContext().getContextPath();
             System.out.println(path+"mmmmmmmmmmm");
            this.getServletContext().getRequestDispatcher("/showJfreeChart.jsp").forward(request, response);
        } finally { 
            try { 
                fos_jpg.close(); 
            } catch (Exception e) {} 
        } 
    }

}
原文地址:https://www.cnblogs.com/ITtangtang/p/2509007.html