2010.03.08 - JfreeChart of the pie, as well as the steps and the three results demonstrate the way

2010.03.08 - JfreeChart of the pie, as well as the steps and the three results demonstrate the method reference: http://blog.csdn.net/qjyong/archive/2009/12/08/4967705.aspx

1, JfreeChart the basic steps:
1, the establishment of Dataset, create a data set all data objects are stored in the Dataset. (Create a data source (dataset) to include will be displayed in the graph data)
2, the establishment of JFreeChart, create a chart
3, select the results of the output approach.

Important classes and interfaces:
org.jfree.data.general.Dataset all data source types must implement interface
org.jfree.chart.ChartFactory by it to generate a JFreeChart object
org.jfree.chart.JFreeChart all the right graphics adjustment is through it Oh! !
org.jfree.chart.plot.Plot get it through the JFreeChart object, and then through the outer portion of its graphics (example: axis) Adjustment Note: it has many sub-categories are generally related to it under the subclass!
org.jfree.chart.renderer.AbstractRenderer get it through the JFreeChart object, and then through its internal part of the graph (example: Line type) to adjust. Similarly, for different types of statements of plans, which have different sub-classes to achieve! In the following we may refer to it as Renderer

Second, the results demonstrate three ways:
1. Output Chart to Swing method window, see below drawToFrame
2. Output graph to disk, see below drawToOutputStream method
3. Output chart to the page

3, pie

package test;   

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;   

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;   

/**
 *  Draw a pie chart using JFreeChart
 * @author qiujy
 */
public class PieChartTest {   

    /**
     * step1: Create a DataSet object
     * @return
     */
    public static PieDataset createDataSet() {
        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;
    }   

    /**
     * step2: Create a chart
     * @param dataset
     * @return
     */
    public static JFreeChart createChart(PieDataset dataset) {
         JFreeChart chart = ChartFactory.createPieChart3D(
        //JFreeChart chart = ChartFactory.createPieChart(
                " Original book sales statistics ",//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(" Original books statistics  ", 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  , You can also draw counterclockwise
        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 garbled  : You have to set the font
        plot.setLabelFont(new Font(" Calligraphy  ", Font.PLAIN, 12));
        //  Sector separation shows, on the  3D Map is not the onset
        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 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 a pie chart  : Circular  (true)  Or oval  (false)
        plot.setCircular(false);
        //  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;
    }   

    /**
     * [color=olive]step3:  Export the chart to the  Swing Frame[/color]
     * @param chart
     */
    public static void drawToFrame(JFreeChart chart){
        // Export the chart to the  Swing Frame
        ChartFrame frame = new ChartFrame(" Original books statistics  ", chart);
        frame.pack();
        frame.setVisible(true);
    }   

    /**
     * [color=olive]step3:  The output graph to the specified disk  [/color]
     * @param destPath
     * @param chart
     */
    public static void drawToOutputStream(String destPath, JFreeChart chart) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(destPath);
            // ChartUtilities.writeChartAsJPEG(
            ChartUtilities.writeChartAsPNG(fos, //  Specifies the target output stream
                    chart, //  A chart object
                    600, //  Width
                    400, //  High
                    null); // ChartRenderingInfo Information
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {   fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }   

     /**
     * [color=olive]step3:  Output chart to a Web page  [/color]
     * @param destPath
     * @param chart
     */
    public static String drawToHtml(JFreeChart chart,HttpSession session,PrintWriter out){
        ChartRenderingInfo info = new ChartRenderingInfo(
                new StandardEntityCollection());
        String fileName = "";
        try
        {
            fileName = ServletUtilities.saveChartAsPNG(chart, 500, 300, info,
                    session);// Generate pictures
//          Write the image map to the PrintWriter
            ChartUtilities.writeImageMap(out, fileName, info, false);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        out.flush();
        return fileName;// Returns the generated name of the picture
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        // step1: Create a DataSet object
//        PieDataset dataset = createDataSet();
//
//        // step2: Create a chart
//        JFreeChart chart = createChart(dataset);
//
//        // step3:  Output chart to Swing window
//        //drawToFrame(chart);
//
//        // step3:  Output chart to disk
//        drawToOutputStream("D:\\mybook-pie.png", chart);
//    }
}

If it is entered into the page

pieChart.jsp

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="pojo.PieChartTest"%>
<%@ page import = "java.io.PrintWriter" %>
<%
PieChartTest chart=new PieChartTest();
String fileName=chart.drawToHtml(chart.createChart(chart.createDataSet()),session,new PrintWriter(out));
  String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + fileName;
%>
<html>
<head>
<title> JFreeChart Usage example  </title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<img src="<%= graphURL %>" width="500" height="300" border="0" usemap="#<%= fileName %>">// Note that this  "#"
</body>
</html>
分类:Java 时间:2008-09-21 人气:472
分享到:
blog comments powered by Disqus

相关文章

  • Java import. Export Excel 2010-08-09

    Current B / S model has become a mainstream application development, and in the business office systems, often have customers like this requirement: You should report directly with our Excel to open (the telecommunications system, the banking system)

  • oracl create the table space. users. authorization and data import and import data PostgreSQL 2011-01-05

    1. Using PL / SQL tool to t_cms_user.dmp into oracle database 1), delete the user and table space in preparation for later drop user uuu cascade; drop tablespace test; 2), re-create the table space and the user and the user authorized to create a tab

  • oracl create table space users. PostgreSQL authorization and data import and import data 2011-01-05

    1 use PL / SQL tools to t_cms_user.dmp into oracle database 1), delete the user and table space to prepare for the back drop user uuu cascade; drop tablespace test; 2), re-create the table space and the user and the user authorized to create the tabl

  • oem error "java.lang.Exception: IOException in send -" 2010-04-26

    oracle 10g R2 EM management console login, header error as follows: "Java.lang.Exception: IOException in sending Request:: Connection refused: connect" Handled as follows: 1. Stop emagent: [Oracle @ rac1] $ export ORACLE_SID = rac1 [Oracle @ rac

  • Companies a method of examination questions - sort of large data integer 2010-09-18

    Subject to the effect: Moving Companies need to have been issued to all 139 numbers for statistical ranking, has issued a document section 139 numbers are stored in a text file (the original title is in two files), a number line, now need to file to

  • hibernate the session.createQuery () method of finding out the solution of data 2011-04-29

    hibernate the session.createQuery () method of finding out the solution of data In the Hibernate configuration file add the following code: <property name="hibernate.query.factory_class"> org.hibernate.hql.classic.ClassicQueryTranslatorFac

  • opencsv java import csv and xls files summary 2010-04-13

    If the binary file into csv or xls file format needed jxl.jar package to resolve, If the file is comma delimited csv format text file is needed opencsv.jar package to resolve. How to distinguish a binary file format, a simple way to use Notepad to op

  • javascript import include import the data type check function 2010-09-12

    function isAlien(a) { return isObject(a) && typeof a.constructor != 'function'; } function isArray(a) { return isObject(a) && a.constructor == Array; } function isBoolean(a) { return typeof a == 'boolean'; } function isEmpty(o) { var i, v;

  • java import in Excel 2010-11-26

    ********************** Excel 95-03 edition read method ******************** ******** private static void readExcel (InputStream inp) throws BiffException, IOException, SQLException { String id, name; jxl.Workbook wb = jxl.Workbook.getWorkbook (inp);

  • @ Import css import link and the difference between 2010-11-19

    Which was raised in the group link and @ import the difference, think of it, I really do not know the reason that google a bit to record this. First show how the wording of the two Most sites use the link method: <link rel="stylesheet" href=&

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

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

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

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