1. 程式人生 > >JFreeChart建立區域圖

JFreeChart建立區域圖

import java.awt.Color;
import java.awt.Font;
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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.PiePlot;
import org.jfree.chart.plot.PlotOrientation;  
import org.jfree.data.category.CategoryDataset;  
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;  

public class CreateJFreeChartArea {
	
	/**    
     * 建立JFreeChart Area Chart(區域圖)    
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
     */    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {     
        //步驟1:建立CategoryDataset物件(準備資料)    	
        CategoryDataset dataset = createDataset();     
        //步驟2:根據Dataset 生成JFreeChart物件,以及做相應的設定     
        JFreeChart freeChart = createChart(dataset);     
        //步驟3:將JFreeChart物件輸出到檔案,Servlet輸出流等       
        saveAsFile(freeChart, "G:\\jfreechart\\area1.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物件:ChartFactory.createAreaChart     
        JFreeChart jfreechart = ChartFactory.createAreaChart("銷售曲線彙總",    //標題     
                "月份",    //categoryAxisLabel (category軸,橫軸,X軸標籤)     
                "數量",    //valueAxisLabel(value軸,縱軸,Y軸的標籤)     
                categoryDataset, // dataset     
                PlotOrientation.VERTICAL,     
                true, // legend     
                false, // tooltips     
                false); // URLs     
             
        //使用CategoryPlot設定各種引數。以下設定可以省略。     
        CategoryPlot  plot = (CategoryPlot) jfreechart.getPlot(); 
        
        //背景色 透明度     
        plot.setBackgroundAlpha(0f);     
        //前景色 透明度     
        plot.setForegroundAlpha(0.5f);     
        //其他設定 參考 CategoryPlot類     
        jfreechart.setBackgroundPaint(Color.white); // 設定背景色為白色
        CategoryPlot categoryplot = jfreechart.getCategoryPlot(); // 獲得
                       
        categoryplot.setBackgroundPaint(Color.lightGray); // 設定圖表資料顯示部分背景色
        categoryplot.setDomainGridlinePaint(Color.white); // 橫座標網格線白色
        categoryplot.setDomainGridlinesVisible(false); // 可見
        categoryplot.setRangeGridlinePaint(Color.white); // 縱座標網格線白色
        
        // 解決中文亂碼問題,共要處理這三部分
        // 1、對標題
        Font font1 = new Font("SansSerif", 10, 20); // 設定字型、型別、字號
        // Font font1 = new Font("SimSun", 10, 20); //也可以
        jfreechart.getTitle().setFont(font1); // 標題
        // 2、對圖裡面的漢字設定,也就是Plot的設定
        Font font2 = new Font("SansSerif", 10, 16); // 設定字型、型別、字號
        categoryplot.getDomainAxis().setLabelFont(font2);// 相當於橫軸或理解為X軸
        categoryplot.getRangeAxis().setLabelFont(font2);// 相當於豎軸理解為Y軸
        // 3、下面的方塊區域是 LegendTitle 物件
        Font font3 = new Font("SansSerif", 10, 12); // 設定字型、型別、字號
        jfreechart.getLegend().setItemFont(font3);// 最下方
             
        return jfreechart;     
    }     
    
    /**    
     * 建立CategoryDataset物件    
     * @throws SQLException 
     * @throws ClassNotFoundException 
     *     
     */    
    public static CategoryDataset createDataset() throws SQLException, ClassNotFoundException {     
             
    	/* Create SQL Database Connection */     
        Class.forName( "com.mysql.jdbc.Driver" );
        Connection connect = DriverManager.getConnection( 
        "jdbc:mysql://localhost:3306/charttest" ,     
        "root",     
        "123");
        
        Statement statement = connect.createStatement( );
        ResultSet resultSet = statement.executeQuery("SELECT product.Product_Name,sale.year,sale.month,sale.sales FROM sale INNER JOIN product ON product.Product_ID=sale.product_Id where product.Product_ID='11' AND year='2017' ORDER BY month" );
        DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();
        
        while( resultSet.next( ) ) 
        {
        	 categoryDataset.addValue(Double.parseDouble( resultSet.getString( "sales" )), 
        	 resultSet.getString( "Product_Name" ),  resultSet.getString( "month" ));
        }
        return categoryDataset;
    }     

}
  3.效果圖