- package com.potevio.rnd;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.jfree.chart.ChartFactory;
- import org.jfree.chart.ChartUtilities;
- import org.jfree.chart.JFreeChart;
- import org.jfree.chart.plot.CategoryPlot;
- import org.jfree.chart.plot.PlotOrientation;
- import org.jfree.data.category.CategoryDataset;
- import org.jfree.data.general.DatasetUtilities;
- public class CreateJFreeChartBar {
- /**
- * 創建JFreeChart Bar Chart(柱狀圖)
- */
- public static void main(String[] args) {
- //步驟1:創建CategoryDataset對象(准備數據)
- CategoryDataset dataset = createDataset();
- //步驟2:根據Dataset 生成JFreeChart對象,以及做相應的設置
- JFreeChart freeChart = createChart(dataset);
- //步驟3:將JFreeChart對象輸出到文件,Servlet輸出流等
- saveAsFile(freeChart, "F:\\jfreechart\\bar.png", 500, 400);
- }
- //保存為文件
- public static void saveAsFile(JFreeChart chart, String outputPath, int weight, int height) {
- FileOutputStream out = null;
- try {
- File outFile = new File(outputPath);
- if (!outFile.getParentFile().exists()) {
- outFile.getParentFile().mkdirs();
- }
- out = new FileOutputStream(outputPath);
- //保存為PNG文件
- ChartUtilities.writeChartAsPNG(out, chart, weight, height);
- //保存為JPEG文件
- //ChartUtilities.writeChartAsJPEG(out, chart, weight, height);
- out.flush();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- //do nothing
- }
- }
- }
- }
- //根據CategoryDataset生成JFreeChart對象
- public static JFreeChart createChart(CategoryDataset categoryDataset) {
- JFreeChart jfreechart = ChartFactory.createBarChart("Bar Chart Demo", //標題
- "產品", //categoryAxisLabel (category軸,橫軸,X軸的標簽)
- "數量", //valueAxisLabel(value軸,縱軸,Y軸的標簽)
- categoryDataset, // dataset
- PlotOrientation.VERTICAL,
- true, // legend
- false, // tooltips
- false); // URLs
- //以下的設置可以由用戶定制,也可以省略
- CategoryPlot plot = (CategoryPlot) jfreechart.getPlot();
- //背景色 透明度
- plot.setBackgroundAlpha(0.5f);
- //前景色 透明度
- plot.setForegroundAlpha(0.5f);
- //其它設置可以參考 CategoryPlot
- return jfreechart;
- }
- /**
- * 創建CategoryDataset對象
- *
- */
- public static CategoryDataset createDataset() {
- String []rowKeys = {"One", "Two", "Three"};
- String []colKeys = {"1987", "1997", "2007"};
- double [][] data = {
- {50, 20, 30},
- {20, 10D, 40D},
- {40, 30.0008D, 38.24D},
- };
- //也可以使用以下代碼
- //DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
- //categoryDataset.addValue(10, "rowKey", "colKey");
- return DatasetUtilities.createCategoryDataset(rowKeys, colKeys, data);
- }
- }
運行效果圖: