JFreeChart package tools

package com.wasu.itv.common.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.xfire.addressing.RandomGUID;
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.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.util.Rotation;

public class JFreeChartUtils {

        /**
         * step2: Create a PieChart chart  
         * 
         * @param dataset
         * @return
         */
        private static JFreeChart createPieChart(DefaultPieDataset dataset,
                        String title,boolean is3D) {
                JFreeChart chart=null;
                if(is3D){
                        chart=ChartFactory.createPieChart3D(
                                        title, //  Chart title  
                                        dataset, //  A data set  
                                        true, //  Whether to display the legend  
                                        true, //  Whether or not ToolTips will show  
                                        true //  Whether generated URL  
                                        );
                }
                else{ chart = ChartFactory.createPieChart(
                                title, //  Chart title  
                                dataset, //  A data set  
                                true, //  Whether to display the legend  
                                true, //  Whether or not ToolTips will show  
                                true //  Whether generated URL  
                                );
                }
                //  Sets the title font  == In order to prevent the garbled: you have to set the font  
                chart.setTitle(new TextTitle(title, new Font(" Blackbody  ", Font.ITALIC, 22)));
                //  Sets the font of the legend  == In order to prevent the garbled: you have to set the font  
                chart.getLegend().setItemFont(new Font(" Blackbody  ", Font.BOLD, 12));
                //  Gets the pie chart Plot object  ( The actual chart  )
                PiePlot plot = (PiePlot) chart.getPlot();
                //  Graphic border color  
                plot.setBaseSectionOutlinePaint(Color.GRAY);
                //  Graphic border thickness  
                plot.setBaseSectionOutlineStroke(new BasicStroke(0.0f));
                //  Set the drawing direction of a pie chart, you can draw clockwise or counter-clockwise draw  
                plot.setDirection(Rotation.ANTICLOCKWISE);
                //  To set a draft angle  ( Graphics rotation angle  )
                plot.setStartAngle(70);
                //  Set highlight a block of data  
                // plot.setExplodePercent("One", 0.1D);
                //  Sets the background color transparency  
                plot.setBackgroundAlpha(0.7F);
                //  Sets the foreground color transparency  
                plot.setForegroundAlpha(0.65F);
                //  Sets the font of the block tag  == In order to prevent the garbled: you have to set the font  
                plot.setLabelFont(new Font(" Tahoma  ", Font.PLAIN, 12));
                //  Sector separation shows  , On the 3D map is not the onset  
                if(is3D)
                        plot.setExplodePercent(dataset.getKey(3), 0.1D);
                //  The legend displays percentage  : Custom mode,  {0}  Represents the options,  {1}  Represents a numeric value  {2}  Represents the percentage of  , A two-digit after the decimal point  
                plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                                "{0}:{1}\r\n({2})", NumberFormat.getNumberInstance(),
                                new DecimalFormat("0.00%")));
                //  The legend displays percentage  
                // plot.setLegendLabelGenerator(new
                // StandardPieSectionLabelGenerator("{0}={1}({2})"));
                //  Specifies the display of pie charts: circular  (true)  Or oval  (false)
                plot.setCircular(true);
                //  There is no time to display  
                plot.setNoDataMessage(" The available data could not be found  ...");

                //  Sets the mouse-over tips  
                plot.setToolTipGenerator(new StandardPieToolTipGenerator());
                //  Sets the hot links  
                // plot.setURLGenerator(new StandardPieURLGenerator("detail.jsp"));

                return chart;
        }

        private static JFreeChart createBarChart(CategoryDataset dataset,
                        String title, String x, String y,boolean is3D) {
                JFreeChart chart =null;
                if(is3D){
                        chart = ChartFactory.createBarChart3D( // 3D The bar chart  
                                        // JFreeChart chart = ChartFactory.createLineChart3D( //3D A line chart  
                                        title, //  The title of a chart  
                                        x, //  Display label directory axis  
                                        y, //  Value axis display label  
                                        dataset, //  A data set  
                                        PlotOrientation.VERTICAL, //  Chart: V vertical  ;H Level  
                                        true, //  Whether to display the legend  
                                        false, //  Whether or not ToolTips will show  
                                        false //  Whether generated URL  
                                        );
                }else{
                        chart = ChartFactory.createBarChart( //  The bar chart  
                                        // JFreeChart chart = ChartFactory.createLineChart3D( //3D A line chart  
                                        title, //  The title of a chart  
                                        x, //  Display label directory axis  
                                        y, //  Value axis display label  
                                        dataset, //  A data set  
                                        PlotOrientation.VERTICAL, //  Chart: V vertical  ;H Level  
                                        true, //  Whether to display the legend  
                                        false, //  Whether or not ToolTips will show  
                                        false //  Whether generated URL  
                                        );
                }
                

                // =============== In order to prevent the garbled: you have to set the font  
                chart.setTitle(new TextTitle(title, new Font(" Blackbody  ", Font.ITALIC, 22)));

                LegendTitle legend = chart.getLegend(); //  Gets a legend  
                legend.setItemFont(new Font(" Tahoma  ", Font.BOLD, 12)); //  Sets the font of the legend, prevent garbled  

                CategoryPlot plot = (CategoryPlot) chart.getPlot(); //  Gets the column chart Plot object  ( The actual chart  )
                //  Sets the column map background color (note that the system takes the color when you use the 16-bit mode to view the color coding, so more accurate)  
                plot.setBackgroundPaint(new Color(255, 255, 204));
                plot.setForegroundAlpha(0.65F); //  Sets the foreground color transparency  

                //  Setting visible horizontal dash  
                plot.setRangeGridlinesVisible(true);
                //  Dash color  
                plot.setRangeGridlinePaint(Color.gray);

                CategoryAxis h = plot.getDomainAxis(); //  Gets the x-axis  
                h.setMaximumCategoryLabelWidthRatio(1.0f);//  The horizontal axis is the Lable on full display  
                h.setLabelFont(new Font(" Tahoma  ", Font.BOLD, 12));//  Set the font, prevent garbled  
                h.setTickLabelFont(new Font(" Tahoma  ", Font.BOLD, 12));//  Numerical axis  
                // h.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//45 Tilted  

                plot.getRangeAxis().setLabelFont(new Font(" Tahoma  ", Font.BOLD, 12)); // Y Axis settings for font, prevent garbled  

                //  Column chart renderer  
                BarRenderer renderer = new BarRenderer();
                //  Sets the column width  
                // renderer.setMaximumBarWidth(0.05);
                //  Sets the height of the pillars  
                // renderer.setMinimumBarLength(0.2);
                //  Sets the color of the border posts  
                renderer.setBaseOutlinePaint(Color.BLACK);
                //  Sets the column border visible  
                renderer.setDrawBarOutline(true);
                //  Sets the color of each column  
                renderer.setSeriesPaint(0, Color.BLUE);
                renderer.setSeriesPaint(1, Color.GREEN);
                renderer.setSeriesPaint(2, Color.RED);
                //  Set each region contains the distance between parallel columns  
                renderer.setItemMargin(0.05);
                //  Displays the numeric value of each column, and modify the value of font property  
                renderer.setIncludeBaseInRange(true);
                renderer
                                .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
                renderer.setBaseItemLabelsVisible(true);
                //  Set the transparency of the column  
                plot.setForegroundAlpha(1.0f);
                //  To add a column chart renderer  
                plot.setRenderer(renderer);

                //  There is no time to display  
                plot.setNoDataMessage(" The available data could not be found  ...");

                return chart;
        }

        /**
         * 
         * @param data
         * @param title
         * @param x
         * @param y
         * @param width
         * @param heigth
         * @param request
         * @return
         */
        public static String generateBarChart(List<Object[]> data, String title,
                        String x, String y, int width, int heigth,boolean is3D,
                        HttpServletRequest request) {
                boolean returnValue = false;
                DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                for (Iterator<Object[]> iterator = data.iterator(); iterator.hasNext();) {
                        Object[] o = (Object[]) iterator.next();
                        dataset.setValue(((Long) o[1]).intValue(), o[0] + ":" + o[1],
                                        o[2].toString());
                }
                JFreeChart chart = createBarChart(dataset, title, x, y,is3D);
                
                RandomGUID guid = new RandomGUID();
                SimpleDateFormat df = new SimpleDateFormat("/yyyy/MM/dd/");
                String subPath = df.format(new Timestamp(System.currentTimeMillis())) +guid.valueAfterMD5 + ".jpg";
                String returnPath="/images/itv/chart/"+subPath;
                
                File f=new File(request.getSession().getServletContext().getRealPath("/")+ returnPath);
                f.getParentFile().mkdirs();
                returnValue = drawToOutputStream(f.getAbsolutePath(), chart, width, heigth);
                return returnPath;
        }
        
        public static String generatePieChart(List<Object[]> data, String title,
                        int width, int heigth, HttpServletRequest request,boolean is3D) {
                boolean returnValue = false;
                DefaultPieDataset dataset = new DefaultPieDataset();
                for (Iterator<Object[]> iterator = data.iterator(); iterator.hasNext();) {
                        Object[] o = (Object[]) iterator.next();
                        dataset.setValue(o[0].toString(), ((Long) o[1]).doubleValue());
                }
                JFreeChart chart = createPieChart(dataset, title,is3D);
                RandomGUID guid = new RandomGUID();
                SimpleDateFormat df = new SimpleDateFormat("/yyyy/MM/dd/");
                String subPath = df.format(new Timestamp(System.currentTimeMillis())) +guid.valueAfterMD5 + ".jpg";
                String returnPath="/images/itv/chart/"+subPath;
                
                File f=new File(request.getSession().getServletContext().getRealPath("/")+ returnPath);
                f.getParentFile().mkdirs();
                returnValue = drawToOutputStream(f.getAbsolutePath(), chart, width, heigth);
                return returnPath;
        }
        
        /**
         * step3:  The output graph to the specified disk  
         * 
         * @param destPath
         * @param chart
         */
        private static boolean drawToOutputStream(String destPath,
                        JFreeChart chart, int width, int heigth) {
                FileOutputStream fos = null;
                boolean returnValue = true;
                try {
                        fos = new FileOutputStream(destPath);
                        ChartUtilities.writeChartAsPNG(fos, //  Specifies the target output stream  
                                        chart, //  A chart object  
                                        width, //  Width  
                                        heigth, //  High  
                                        null); // ChartRenderingInfo Information  
                } catch (IOException e) {
                        e.printStackTrace();
                        returnValue = false;
                } finally {
                        try {
                                fos.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                }
                return returnValue;
        }

        /**
         * @param args
         */
        public static void main(String[] args) {
                
                CategoryDataset  dataset = createBarDataSet2();
                JFreeChart chart=createBarChart(dataset, "111111111111111", "2222222", "2222222",true);
                drawToOutputStream("D:\\mybook-pie.png", chart, 640, 480);
        }

        private static DefaultPieDataset createPieDataSet1() {
                DefaultPieDataset dataset = new DefaultPieDataset();
                dataset.setValue("java Programming language  ", 10000);
                dataset.setValue("JSP Detailed description of the basic and case development  ", 20000);
                dataset.setValue("struts Detailed description of the basic and case development  ", 30000);
                dataset.setValue(" Proficient in JSF  ", 40000);

                return dataset;
        }

        private static DefaultPieDataset createPieDataSet2() {
                DefaultPieDataset dataset = new DefaultPieDataset();
                dataset.setValue("  Market  ", new Double(10));
                dataset.setValue("  Project  ", new Double(15));
                dataset.setValue("  Plan  ", new Double(10));
                dataset.setValue("  Requirements and design  ", new Double(10));
                dataset.setValue("  Execution control  ", new Double(35));
                dataset.setValue("  In the ending  ", new Double(10));
                dataset.setValue("  Operation and maintenance  ", new Double(10));
                return dataset;
        }

        /**
         * step1: Creates a simple DataSet object  
         * 
         * @return
         */
        private static CategoryDataset createBarDataSet1() {
                DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                dataset.setValue(10000, "", "Corejava");
                dataset.setValue(20000, "", "JavaWeb");
                dataset.setValue(30000, "", " Easy-to-use struts  ");
                dataset.setValue(40000, "", " Proficient in JSF  ");

                return dataset;
        }

        /**
         *  The combined data set object  
         * 
         * @return
         */
        private static CategoryDataset createBarDataSet2() {
                DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                dataset.setValue(5000, " Beijing  ", "Corejava");
                dataset.setValue(3000, " Shanghai  ", "Corejava");
                dataset.setValue(2000, " Guangzhou  ", "Corejava");

                dataset.setValue(10000, " Beijing  ", "JavaWeb");
                dataset.setValue(6000, " Shanghai  ", "JavaWeb");
                dataset.setValue(4000, " Guangzhou  ", "JavaWeb");

                dataset.setValue(15000, " Beijing  ", " Easy-to-use struts  ");
                dataset.setValue(5000, " Shanghai  ", " Easy-to-use struts  ");
                dataset.setValue(10000, " Guangzhou  ", " Easy-to-use struts  ");

                dataset.setValue(20000, " Beijing  ", " Proficient in JSF  ");
                dataset.setValue(10000, " Shanghai  ", " Proficient in JSF  ");
                dataset.setValue(10000, " Guangzhou  ", " Proficient in JSF  ");

                return dataset;
        }

}
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of JFreeChart package tools

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • can not be represented as java.sql.Timestamp

    Development of procedures for the use of hibernate when, some time there is no need to fill in the fields, but after the hibernate query time reported "Java.sql.SQLException: Value'0000-00-00 'can not be represented as java.sql.Timestamp ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Hibernate annotation using notebook

    These are the basic common @Entity --Declared an entity bean @Table(name="promotion_info") --For the entity bean mapping for the specified table (Table name ="promotion_info) @Id --Declare that the identifying attribute of the entity bean @GeneratedValue

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries