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;
        }

}
分类:Java 时间:2010-03-29 人气:585
分享到:
blog comments powered by Disqus

相关文章

  • Java data type, Hibernate data types, standard sql data type correspondence table between 2010-05-13

    Hibernate API Introduction Its interface is divided into the following categories: l provide access to the database operation interface; l used to configure the Hibernate interfaces; l callback interfaces l extend Hibernate functionality of the inter

  • pl / sql import and export 2011-05-16

    Summary and some of their own small record Export table structure: Tools -> Export User Objects (export user objects) -> choose to export the table (including the Sequence so )-->. sql files, sql files are exported Export table data: Tools ->

  • Bash string processing (and Java control) - 17 to determine whether the other end of the string 2011-10-09

    Bash string processing (and Java control) - 17 to determine whether the other end of the string In Java String.endsWith oolean endsWith (String suffix) Test whether this string ends with the specified suffix. StringUtils.endsWith & StringUtils.endsWi

  • (SQL error) DB2 SQL error: SQLCODE: -418, SQLSTATE: 42610, SQLERRMC: null 2011-03-08

    (SQL error) DB2 SQL error: SQLCODE: -418, SQLSTATE: 42610, SQLERRMC: null db no problem in the implementation, java call execution time error. Baidu was the answer: Result set, you can not pass parameters Parameter markers can never be used: * In a s

  • SQL Tuning 34 [SQL Collection] 2011-06-26

    SQL Tuning 34 [SQL Collection] Description: Very practical SQL optimization, but also developers write SQL required attention, very grateful to the author's dedication, to do the classic article collection for learning exchanges. Not only do we have

  • 监控和剖析数据库操作-P6Spy.SQL Profiler.IronTrack SQL 使用简介 2012-11-05

    在我们 Java 开发应用程序的过程中,难免会碰到系统的性能问题,特别在企业应用的开发过程中,都会与数据库进行打交道.当我们碰到数据库性能时,最有效的就是直接跟踪每一个 SQL 语句的执行情况,SQL 语句的优化.索引的优化往往也是最容易取得最直接的效果的. 下面,我们首先开始介绍 P6Spy 这个剖析工具,看它是如何无侵入性地进行数据库操作的监控与剖析. P6Spy P6Spy 是一个可以用来在应用程序中拦截和修改数据操作语句的开源框架.通过 P6Spy 我们可以对 SQL 语句进行拦截,相当

  • sql union and sql union all of the usage and efficiency 2010-03-04

    1, sql union usage sql union query SQL statements can be the result of the two combined. If you look at it this way, UNION JOIN is similar with the two commands can retrieve data from the multiple tables. sql union of a limit of two SQL statements ge

  • oracle and sql server query SQL statement page 2010-03-25

    1.Oracle paging sql statement SELECT * FROM (SELECT A.*, ROWNUM RN FROM ( select sno,sname,sage,ssex from tb_student where 1=1 ) A WHERE ROWNUM <'24') WHERE RN >='0' 2.Sql Server paging sql statement SELECT sno,sname,sage,ssex FROM ( SELECT ROW_NUMB

  • This function has none of DETERMINISTIC, NO SQL, or READS SQL 2010-06-29

    This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary This warning is rising because as the default MySQL server supports replication. This means that BINARY LOGGING is turned ON. So, there is a replication

  • Storing settings for SQL * PLUS (login.sql and glogin.sql) 2010-07-19

    Source: http://www.adp-gmbh.ch/ora/sqlplus/login.html Storing settings for SQL * PLUS (login.sql and glogin.sql) glogin.sql Whenever SQL * PLUS starts up, it looks for a file named glogin.sql under the directory $ ORACLE_HOME / sqlplus / admin. If su

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.740 (s). 12 q(s)