Java make chart (report)--jfreechart Comprehensive application

Source: Internet
Author: User
Tags class definition flush pear
Jfreechart is an open source JAVA project that is designed to develop a wide variety of charts, including pie, histogram (plain column and stack bar), line, area, map, blending, Gantt Chart, and some dashboards. In these different patterns of graphics can meet the requirements of the current business system. Jfreechart is a graphical development technology based on the JAVA language. Jfreechart can be used in Servlet, JSP, applet, Java appication environment, can dynamically display any database data through JDBC, combine Itext can output to PDF file. Jfreechart is mainly composed of three classes: A) Org.jfree.chart.servlet.ChartDeleter inherits from Httpsessionbindinglistener, which is used to implement when the session is closed Deletes the image file in the temporary eye. B) Org.jfree.chart.servlet.DisplayChart inherits from HttpServlet for processing display images. C) Org.jfree.chart.servlet.ServletUtilities has a series of methods, for example, savechartas*;savechartas* is to store charts in different forms as images; sendtempfile The method is overloaded many times to send the file stream response. The following is an example of a bar chart and a pie chart that describes how to create a graphic. 1 Columnar Chart Org.jfree.chart.ChartFactory This factory class has Createbarchart, Createstackedbarchart, Createbarchart3d, Createstackedbarchart3d, these factory methods create different types of columnar graphs, it is more important that plotorientation.vertical let parallel columns appear vertically, while plotorientation.horizontal Let the parallel column be displayed horizontally. Several classes that have a larger impact on the histogram include: Org.jfree.chart.axis.CategoryAxis, Org.jfree.chart.axis.ValueAxis, Org.jfree.chart.renderer.BarRenderer, Org.jfree.chart.renderer. BaRrenderer3d. Implementation steps: 1 Create the DataSet object you want for the graphics generation. Categorydataset DataSet = Datasetutilities.createcategorydataset (Rowkeys, Columnkeys, data) Where: Rowkeys represents X-axis data, column The Keys represent the Y-axis data, which represents the actual data (from the database) to fill the histogram. 2 Create a drawing object. Jfreechart chart = Chartfactory.createbarchart3d ("title",  null, NULL, DataSet, Plotorientation.vertical,, True, F Alse, False); Createbarchart3d method is a method in the Chartfactory factory class for 3D histogram generation, which inherits from Jfreechart. The eight parameters are: the caption of the graph, the X axis title, the Y-axis title, the dataset is the instance object of the Categorydataset class, the display title, the hotkey enabled, and the Hyper-key access enabled. 3 Set the properties of the graphic display. A) Valueaxis class, set the distance between the column and the bottom of the graph. The realization method is: Valueaxis Rangeaxis = Plot.getrangeaxis (); Set the highest column distance from the top of the picture: Rangeaxis.setuppermargin (0.15) Set the minimum distance between one column and the bottom of the picture: Rangeaxis.setlowermargin (0.15) b) Org.jfree.chart.renderer.BarRenderer3D class, set the values displayed on the graph. The implementation method is as follows: Barrenderer3d renderer = new Barrenderer3d (); Renderer.setbaseoutlinepaint (Color.Black); Set the color of the Wall: Renderer.setwallpaint (Color.gray); Set the color of each column: Renderer.setseriespaint (0, new color (0, 0, 255)); Renderer.setseriespaint (1, New COlor (0, 100, 255)); Renderer.setseriespaint (2, Color.green); Set the Outline color of each column
Renderer.setseriesoutlinepaint (0, Color.Black); Renderer.setseriesoutlinepaint (1, Color.Black); Renderer.setseriesoutlinepaint (2, Color.Black); Set the distance between the parallel columns contained in each region
Renderer.setitemmargin (0.1); Displays the value of each column and modifies the Font property renderer.setitemlabelgenerator (new Standardcategoryitemlabelgenerator ()) of the value. Renderer.setitemlabelfont (New Font ("bold", font.plain,12)); Renderer.setitemlabelsvisible (TRUE); Add a hyperlink Renderer.setitemurlgenerator (new Standardcategoryurlgenerator ()) to the graphic; Renderer.settooltipgenerator (New Standardcategorytooltipgenerator ()); A 2 pie chart Org.jfree.chart.plot package that contains all the methods and properties for creating a pie chart. According to the business needs of the author created a seturlgenerator (Pieurlgenerator generator) method, in the picture to establish a connection, that is, different parts of the picture to connect different resources. Setsectionlabeltype (int type) method: Specifies the type of section label, there are 7 types. If not specified, the default is Name_labels, where the types are: Pieplot.no_labels pieplot.name_labels pieplot.value_labels Pieplot.percent_labels, Pieplot.name_and_value_labels, Pieplot. Name_and_percent_labels, Pieplot.value_and_percent_labels. Setdefaultoutlinepaint (Java.awt.Paint Paint) method that specifies the color of the section contour and, if unspecified, the default value is NULL. Setdefaultoutlinestroke (Java.awt.Stroke Stroke) method that specifies the thickness of the section contour. Setradius (double percent) and setexplodepercent (int section, double percent) method, a section is extracted from the pie chart, which requires two methods to use together. The Setstartangle (double angle) method sets the first section start position, and the default starts at 12 o'clock. The Setpaint (int section, Java.awt.Paint Paint) method specifies the color of the section. The setdirection (int direction) method specifies a section order, which defaults to clockwise direction. Clockwise: pieplot.clockwise; counterclockwise: Pieplot.anticlockwise. Implementation steps: 1 Create the DataSet object you want for the graphics generation. First instantiate the class Defaultpiedataset DataSet = new Defaultpiedataset (). Then, the SetValue (Value1,value2) method provided by the Defaultpiedataset class is used to deposit the data extracted from the database into Defaultpiedataset object. Where value1 is the data name, value2 is the data value. 2 Create a drawing object. First instantiate Jfreechart chart = Chartfactory.createpiechart3d (title, DataSet, True, True, false) The Createpiechart3d method is the primary method used for pie chart generation. Where title represents the title of the graph, the dataset is an instance of the Defaultpiedataset object. 3 Set the properties of the graphic display. String filename = servletutilities.savechartaspng (Jfreechart, M, 450, info, session); Chartutilities.writeimagemap (PW, filename, info); The Pw.flush () Savechartaspng method is completed in the Servletutilities factory class definition. It is mainly used to save graphics objects Jfreechart as pictures. The Jfreechart is an instance of the Jfreechart object. The method returns a file name. The Writeimagemap (PW, filename, info) method is used to write the saved picture file in the form of a byte streaminto the user interface. Where PW is an instance object of the Java.io package's PrintWriter class, which creates a graphics output stream. FileName is the file name of the output picture. The file name is from the Servletutilities.savechartaspng method creation. The parameter info is used to display graphical information. Created with Chartrenderinginfo info=new chartrenderinginfo (New Standardentitycollection ()). The final output completes the graph and calls the Pw.flush () method to close the IO stream.

------------------------------------------------------------------------------------------
Use Jfreechart to generate graphs of various styles limited to space we only implement two commonly used charts here, and other types of chart readers can analogy. We first give the implementation of the histogram, the implementation of the pie chart and then to compare with the bar chart. 1 bar Chart

Package Lius.chart.demo;

Import java.io.*;

Import org.jfree.data.*;
Import org.jfree.chart.*;
Import org.jfree.chart.plot.*;
/**
* This class is used to demonstrate the simplest column graph generation
* @author Winter Lau
*/
public class Barchartdemo {

public static void Main (string[] args) throws ioexception{

Categorydataset DataSet = GetDataSet2 ();
Jfreechart chart = Chartfactory.createbarchart3d (
"Fruit yield map",//Chart title
"Fruit",//the display label of the catalogue axis
"Output",//value axis display label
DataSet,//DataSet
Plotorientation.vertical,//Chart Orientation: horizontal, vertical
True,//whether to display the legend (for a simple bar chart must be false)
False,//whether to generate tools
False//whether to generate URL links
);

FileOutputStream fos_jpg = null;
try {
fos_jpg = new FileOutputStream ("d://fruit.jpg");
Chartutilities.writechartasjpeg (Fos_jpg,100,chart,400,300,null);
finally {
try {
Fos_jpg.close ();
catch (Exception e) {}
}
}
/**
* Get a demo of a simple DataSet object
* @return
*/
private static Categorydataset GetDataSet () {
Defaultcategorydataset DataSet = new Defaultcategorydataset ();
Dataset.addvalue (MB, NULL, "Apple");
Dataset.addvalue (=, null, "pear");
Dataset.addvalue (+, NULL, "grapes");
Dataset.addvalue (n, NULL, "banana");
Dataset.addvalue (+, NULL, "Litchi");
return dataset;
}
/**
* Get a demo of a composite DataSet object
* @return
*/
private static Categorydataset GetDataSet2 () {
Defaultcategorydataset DataSet = new Defaultcategorydataset ();
Dataset.addvalue (100, "Beijing", "Apple");
Dataset.addvalue (100, "Shanghai", "Apple");
Dataset.addvalue (100, "Guangzhou", "Apple");
Dataset.addvalue (200, "Beijing", "pear");
Dataset.addvalue (200, "Shanghai", "pear");
Dataset.addvalue (200, "Guangzhou", "pear");
Dataset.addvalue (300, "Beijing", "grapes");
Dataset.addvalue (300, "Shanghai", "grapes");
Dataset.addvalue (300, "Guangzhou", "Grape");
Dataset.addvalue (400, "Beijing", "banana");
Dataset.addvalue (400, "Shanghai", "banana");
Dataset.addvalue (400, "Guangzhou", "banana");
Dataset.addvalue (500, "Beijing", "Litchi");
Dataset.addvalue (500, "Shanghai", "Litchi");
Dataset.addvalue (500, "Guangzhou", "Litchi");
return dataset;
}
}

The picture file effect that is generated after the program is run is as shown in the following illustration:
Figure 4

The picture file that is generated when you use the GetDataSet method to get a dataset using simple data is as follows:
Figure 5

2 pie charts for pie charts, datasets are not obtained with the same dataset class, and the pie chart does not support data such as subprojects in the same category. We only give the code to create the pie chart, as the chart to a file is consistent with the histogram, without duplicating.

Package Lius.chart.demo;

Import java.io.*;

Import org.jfree.data.*;
Import org.jfree.chart.*;
/**
* Used to demonstrate the generation of pie graphs
* @author Winter Lau
*/
public class Piechartdemo {

public static void Main (string[] args) throws ioexception{
Defaultpiedataset data = GetDataSet ();
Jfreechart chart = chartfactory.createpie3dchart ("Fruit yield map", //Chart title

True,//Whether the legend is displayed
False
False
);
Write chart object to file, generate source code with reference to bar chart
}
/**
* Get a demo of a simple DataSet object
* @return
*/
private static Defaultpiedataset GetDataSet () {
Defaultpiedataset DataSet = new Defaultpiedataset ();
Dataset.setvalue ("Apple", 100);
Dataset.setvalue ("Pear", 200);
Dataset.setvalue ("Grapes", 300);
Dataset.setvalue ("Banana", 400);
Dataset.setvalue ("Litchi", 500);
return dataset;
}
}

The resulting pie-chart file effect is as follows:
Figure 6





Back to the top of the page


move the generated chart to the browser to pass the generated chart directly to the client browser, replace the file stream in the preceding two examples with the output stream obtained through the HttpServletResponse object, with the detailed code listing:
 
Package lius.chart.demo;

Import java.io.IOException;
Import javax.servlet.*;
Import Javax.servlet.http.HttpServlet;

Import org.jfree.data.*;
Import org.jfree.chart.*;
/**
* Demo Direct output chart through servlet
* @author Winter Lau
*/
public class Chartdemoservlet extends HttpServlet {

public void Service (ServletRequest req, servletresponse Res)
throws Servletexception, IOException
{
Re S.setcontenttype ("Image/jpeg");
Defaultpiedataset data = GetDataSet ();
Jfreechart chart = chartfactory.createpie3dchart (fruit yield chart,
data,
True,
False,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.