jfreechart 전체 코드 인 스 턴 스


import java.awt.Color;   
import java.awt.Font;   
import java.io.File;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.util.ArrayList;   
import java.util.HashMap;   
import java.util.List;   
import java.util.Map;   
  
import net.bingosoft.common.config.Config;   
  
import org.apache.commons.logging.Log;   
import org.apache.commons.logging.LogFactory;   
import org.jfree.chart.ChartFactory;   
import org.jfree.chart.ChartUtilities;   
import org.jfree.chart.JFreeChart;   
import org.jfree.chart.axis.CategoryAxis;   
import org.jfree.chart.axis.CategoryLabelPositions;   
import org.jfree.chart.axis.NumberAxis;   
import org.jfree.chart.axis.ValueAxis;   
import org.jfree.chart.labels.ItemLabelAnchor;   
import org.jfree.chart.labels.ItemLabelPosition;   
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;   
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;   
import org.jfree.chart.plot.CategoryPlot;   
import org.jfree.chart.plot.PlotOrientation;   
import org.jfree.chart.renderer.category.BarRenderer;   
import org.jfree.chart.renderer.category.LineAndShapeRenderer;   
import org.jfree.chart.title.TextTitle;   
import org.jfree.data.category.CategoryDataset;   
import org.jfree.data.general.DatasetUtilities;   
import org.jfree.data.general.DefaultPieDataset;   
import org.jfree.data.general.PieDataset;   
import org.jfree.ui.TextAnchor;   
  
public class CreateChartService {   
  
    private static Log log = LogFactory.getLog(CreateChartService.class);   
       
    //           
    private static final String CHART_PATH = Config.getString("image.filepath");      
       
    /**    
     *          
     * 1.    <br>  
     * 2.    ,       ,    List<br>  
     * @throws IOException   
     */     
    public List createLineAndShapeChart(double[][]data , String[]rowKeys,String[] columnKeys,ChartEntity entity) throws IOException {      
        List list = new ArrayList() ;   
        byte[] bytes = new byte[]{} ;   
        //        
        Map map = this.parseDataForBarPage(data, rowKeys, columnKeys) ;   
        int pageNum = Integer.parseInt(""+map.get("pageNum")) ;   
        //   ,          
        for(int i=0 ; i<pageNum ; i++){   
            bytes = createSingleLineAndShapeChart((double[][])(map.get("data"+i)),(String[])(map.get("rowKeys"+i)),   
                    (String[])(map.get("columnKeys"+i)),entity) ;    
            list.add(bytes) ;   
        }   
        return list ;   
    }      
       
    /**  
     *               
     * @param data  
     * @param rowKeys  
     * @param columnKeys  
     * @param entity  
     * @return  
     * @throws IOException  
     */    
    public byte[] createSingleLineAndShapeChart(double[][]data , String[]rowKeys,String[] columnKeys,ChartEntity entity) throws IOException {      
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);      
        JFreeChart chart = createTimeXYChar(dataset, entity);   
        byte[] bytes = this.createImage(chart, entity) ;   
        return bytes ;   
    }      
       
       
    /**  
     *      <br>  
     * 1.    <br>  
     * 2.    ,       ,    List<br>  
     * @param data     
     * @param rowKeys    
     * @param columnKeys    
     * @param entity         
     * @return           List  
     * @throws IOException  
     */  
    public List createStackedBarChart(double[][]data,String[]rowKeys,String[]columnKeys , ChartEntity entity) throws IOException {   
        //        
        List list = new ArrayList() ;   
        byte[] bytes = new byte[]{} ;   
        Map map = this.parseDataForBarPage(data, rowKeys, columnKeys) ;   
        int pageNum = Integer.parseInt(""+map.get("pageNum")) ;   
        //     ,       ,    List   
        for(int i=0 ; i<pageNum ; i++){   
            bytes = createSingleStackedBarChart((double[][])(map.get("data"+i)),(String[])(map.get("rowKeys"+i)),   
                    (String[])(map.get("columnKeys"+i)),entity) ;    
            list.add(bytes) ;   
        }   
        return list ;   
    }   
       
    /**  
     *              
     * @param data  
     * @param rowKeys  
     * @param columnKeys  
     * @return  
     */  
    private Map parseDataForBarPage(double[][]data,String[]rowKeys,String[]columnKeys){   
        Map map = new HashMap() ;   
           
        double [][] pageData = null ;   
        String [] pageColumn = null ;   
           
        int sumColumnNum = columnKeys.length ; //       
        int indexNum = Config.getInt("image.export.pagesize", 10) ;//         
        int pageNum = sumColumnNum%indexNum==0 ? sumColumnNum/indexNum : sumColumnNum/indexNum+1 ; //       
        int rowNum = rowKeys.length ;   
           
//      log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" ");   
           
        //             
        for(int i=0 ; i<pageNum ; i++){   
            int columnNum = (sumColumnNum-i*indexNum)/indexNum>0 ? indexNum : (sumColumnNum-i*indexNum)%indexNum ;//        
            pageData = new double[rowNum][columnNum] ;   
            //        
            for(int j=0 ; j<rowNum ; j++){   
                pageColumn = new String[columnNum] ;   
                for(int k=0 ; k<columnNum ; k ++){   
                    pageData[j][k] = data[j][k+i*indexNum] ; //      
                }   
            }   
            //       
            for(int j=0 ; j<columnNum ; j++){   
                pageColumn[j] = columnKeys[j+i*indexNum] ; //     
            }   
            //           
            map.put("data"+i, pageData) ;   
            map.put("rowKeys"+i, rowKeys) ;   
            map.put("columnKeys"+i, pageColumn) ;   
        }   
        //         
        map.put("pageNum", pageNum);   
        return map ;   
    }   
       
    /**  
     *              
     * @param data  
     * @param rowKeys  
     * @param columnKeys  
     * @return  
     */  
    private Map parseDataForLinePage(double[][]data,String[]rowKeys,String[]columnKeys){   
        Map map = new HashMap() ;   
           
        double [][] pageData = null ;   
        String [] pageColumn = null ;   
           
        int sumColumnNum = columnKeys.length ; //       
        int indexNum = Config.getInt("image.export.pagesize", 10) ;//         
        int pageNum = sumColumnNum%indexNum==0 ? sumColumnNum/indexNum : sumColumnNum/indexNum+1 ; //       
        int rowNum = rowKeys.length ;   
           
//      log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" ");   
           
        //             
        for(int i=0 ; i<pageNum ; i++){   
            int columnNum = (sumColumnNum-i*indexNum)/indexNum>0 ? indexNum : (sumColumnNum-i*indexNum)%indexNum ;//        
            pageData = new double[rowNum][columnNum] ;   
            //        
            for(int j=0 ; j<rowNum ; j++){   
                pageColumn = new String[columnNum] ;   
                for(int k=0 ; k<columnNum ; k ++){   
                    pageData[j][k] = data[j][k+i*indexNum] ; //      
                }   
            }   
            //       
            for(int j=0 ; j<columnNum ; j++){   
                pageColumn[j] = columnKeys[j+i*indexNum] ; //     
            }   
            //           
            map.put("data"+i, pageData) ;   
            map.put("rowKeys"+i, rowKeys) ;   
            map.put("columnKeys"+i, pageColumn) ;   
        }   
        //         
        map.put("pageNum", pageNum);   
        return map ;   
    }   
       
    /**    
     *              
     * @return        
     * @throws IOException   
     */     
    public byte[] createSingleStackedBarChart(double[][]data,String[]rowKeys,String[]columnKeys , ChartEntity entity) throws IOException {      
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);      
        JFreeChart chart = createStackedBarChart(dataset, entity);    
        byte[] bytes = this.createImage(chart, entity) ;   
        return bytes ;   
    }     
       
    //    ,             
    private CategoryDataset getBarData(double[][] data, String[] rowKeys,      
            String[] columnKeys) {      
        return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);      
     
    }      
     
    /**    
     *          ,            
     * @param chartPath    
     */     
    private void isChartPathExist(String chartPath) {      
        File file = new File(chartPath);      
        if (!file.exists()) {      
            file.mkdirs();      
        }      
    }      
     
    /**    
     *        
     *     
     * @param chartTitle    
     * @param x    
     * @param y    
     * @param xyDataset    
     * @param charName    
     * @return    
     */     
    private JFreeChart createTimeXYChar(CategoryDataset xyDataset,ChartEntity entity) {      
     
        JFreeChart chart = ChartFactory.createLineChart(   
                entity.getTitle(),    
                entity.getXname(),    
                entity.getYname(),      
                xyDataset,    
                PlotOrientation.VERTICAL,    
                true,    
                true,    
                false);      
     
        chart.setTextAntiAlias(false);      
        chart.setBackgroundPaint(Color.WHITE);      
     
        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();      
        //           
        this.configNoData(chart, "        !") ;   
           
        // x  //                
        categoryplot.setDomainGridlinesVisible(true);      
        // y  //               
        categoryplot.setRangeGridlinesVisible(true);      
     
        categoryplot.setRangeGridlinePaint(Color.WHITE);//           
     
        categoryplot.setDomainGridlinePaint(Color.WHITE);//           
     
        categoryplot.setBackgroundPaint(Color.lightGray);      
     
           
        //        
        this.configFont(chart) ;   
     
        // x      
        CategoryAxis domainAxis = categoryplot.getDomainAxis();      
           
        //                 
        domainAxis.setLowerMargin(0.0);      
        //                 
        domainAxis.setUpperMargin(0.0);   
        domainAxis.setTickLabelPaint(Color.BLUE) ;   
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); //     label        
     
        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();      
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());      
        numberaxis.setAutoRangeIncludesZero(true);      
     
        //   renderer           lineandshaperenderer!!      
        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();      
        lineandshaperenderer.setBaseShapesVisible(true); // series  (    )        
        lineandshaperenderer.setBaseLinesVisible(true); // series  (    )            
     
        //             
        lineandshaperenderer.setBaseItemLabelGenerator(new      
        StandardCategoryItemLabelGenerator());      
        lineandshaperenderer.setBaseItemLabelsVisible(true);      
           
        return chart ;   
    }      
     
    /**    
     *          
     *     
     * @param dataset    
     * @param xName    
     * @param yName    
     * @param chartTitle    
     * @param charName    
     * @return    
     */     
    private JFreeChart createStackedBarChart(CategoryDataset dataset, ChartEntity entity) {      
           
        JFreeChart chart = ChartFactory.createStackedBarChart3D(   
                entity.getTitle(),    
                entity.getXname(),    
                entity.getYname(),    
                dataset,    
                PlotOrientation.VERTICAL,    
                true,    
                false,    
                false );   
           
        //          
        this.configNoData(chart,"        !") ;   
           
        //        
        this.configFont(chart) ;   
           
        //    Renderer   
        this.configBarRenderer(chart) ;   
           
        //        
        this.configOtherForBar(chart) ;   
           
        return chart ;   
    }      
       
    /**  
     *        
     * @param chart JFreeChart     
     */  
    private void configFont(JFreeChart chart){   
        //        
        Font xfont = new Font("  ",Font.PLAIN,12) ;// X    
        Font yfont = new Font("  ",Font.PLAIN,12) ;// Y    
        Font kfont = new Font("  ",Font.PLAIN,12) ;//      
        Font titleFont = new Font("  ", Font.BOLD , 25) ; //        
        CategoryPlot plot = chart.getCategoryPlot();//             
           
        //        
        chart.setTitle(new TextTitle(chart.getTitle().getText(),titleFont));   
           
        //      
        chart.getLegend().setItemFont(kfont);   
           
        // X     
        CategoryAxis domainAxis = plot.getDomainAxis();      
        domainAxis.setLabelFont(xfont);//       
        domainAxis.setTickLabelFont(xfont);//         
        domainAxis.setTickLabelPaint(Color.BLUE) ; //        
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); //     label       
           
        // Y     
        ValueAxis rangeAxis = plot.getRangeAxis();      
        rangeAxis.setLabelFont(yfont);    
        rangeAxis.setLabelPaint(Color.BLUE) ; //        
        rangeAxis.setTickLabelFont(yfont);     
           
    }   
       
    /**  
     *        
     * @param chart  
     */  
    private void configBarRenderer(JFreeChart chart){   
           
        CategoryPlot categoryplot = (CategoryPlot)chart.getPlot();   
//                     
        ExtendedStackedBarRenderer extendedstackedbarrenderer = new ExtendedStackedBarRenderer();   
        extendedstackedbarrenderer.setBaseItemLabelsVisible(true);   
        extendedstackedbarrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());   
        extendedstackedbarrenderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());   
        categoryplot.setRenderer(extendedstackedbarrenderer);   
           
        BarRenderer barrenderer = (BarRenderer)categoryplot.getRenderer();   
        barrenderer.setDrawBarOutline(false);   
        barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());   
        barrenderer.setBaseItemLabelsVisible(true);   
        barrenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));   
        barrenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));   
           
        //          
//        barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",new DecimalFormat("0.0%")));       
//        barrenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());   
        barrenderer.setItemLabelFont(new Font("Arial Unicode MS",Font.PLAIN,9));     
        barrenderer.setItemLabelsVisible(true);   
           
//                ,         
//      ItemLabelPosition itemLabelPositionFallback=new ItemLabelPosition(   
//              ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT,   
//              TextAnchor.HALF_ASCENT_LEFT,0D);   
//      barrenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);   
//      barrenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);   
           
        categoryplot.setRenderer(barrenderer) ;   
    }   
       
    /**  
     *               
     * @param chart  
     */  
    private void configNoData(JFreeChart chart,String message){   
        CategoryPlot categoryplot = (CategoryPlot)chart.getPlot();   
        //            
        categoryplot.setNoDataMessage(message) ;   
        categoryplot.setNoDataMessageFont(new Font("  ",Font.BOLD,25)) ;   
    }   
       
    /**  
     *       
     * @param chart  
     */  
    private void configOtherForBar(JFreeChart chart){   
    
        chart.setTextAntiAlias(false);   //            
     
        chart.setBackgroundPaint(Color.WHITE); //         
           
        CategoryPlot plot = chart.getCategoryPlot();//             
        NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();      
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());      
        numberaxis.setAutoRangeIncludesZero(true);    
    }   
  
    /**  
     *           
     * @param chart  
     * @param entity         
     * @return        
     * @throws IOException  
     */  
    private byte[] createImage(JFreeChart chart , ChartEntity entity) throws IOException{   
        return ChartUtilities.encodeAsPNG(chart.createBufferedImage(entity.getWidth(), entity.getHeight())) ;   
    }   
       
    /**  
     *            
     * @param chart  
     * @param entity  
     * @throws IOException  
     */  
    private void createImageFile(JFreeChart chart , ChartEntity entity) throws IOException{   
        FileOutputStream fos_jpg = null;      
        try {      
            isChartPathExist(CHART_PATH);      
            String chartName = CHART_PATH + entity.getFileName();      
            fos_jpg = new FileOutputStream(chartName);      
            ChartUtilities.writeChartAsJPEG(fos_jpg, chart, entity.getWidth(), entity.getHeight()) ;   
        } catch (Exception e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                fos_jpg.close();      
            } catch (Exception e) {      
                e.printStackTrace();      
            }      
        }      
    }   
}

좋은 웹페이지 즐겨찾기