1. jfreechart Project Overview
Jfreechart is a Java project on the open source site sourceforge.net. It is mainly used for various charts.
Tables include: pie chart, bar chart (common bar chart and stack column chart), line chart, Area Chart, distribution chart, hybrid chart, Gantt chart and
Some dashboards. These charts of different types can basically meet the current requirements. In order to reduce the length, this article mainly introduces
You can develop other types of charts by analogy. The following three types are generated by jfreechart:
Chart results:
Figure 1
Figure 2
Figure 3
The three figures above indicate the sales information of a product in four quarters. Before proceeding to the following sections, you must prepare the development environment
Because it is based on Web browser charts, a servlet engine or J2EE Application Server (for example
WebSphere, tomcat, etc ). Setting up the web environment is not cumbersome. you can install the environment on your own based on your preferences. Jfreechart engine itself
Download the package from sourceforge.net at the following address:
Jfreechart home: http://www.jfree.org/jfreechart/index.html
Jfreechart download page: http://sourceforge.net/projects/jfreechart/
When downloading, you must download two files: jfreechart and jcommon. The latest supported versions are: jfreechart 0.9.11 jcommon 0.8.6
Here is a bit of a problem I encountered during development. It should be noted that when using eclipse for development, an inexplicable error will be reported, which may point to the first line of a class file. This problem is generally caused by the failure to set the jcommon jar package to the project class path. The specific cause is ominous.
Ii. Interpretation of jfreechart source code structure
Before using jfreechart, it is necessary to take a rough look at the structure of jfreechart and the examples provided by jfreechart.
In this way, we will be able to develop the SDK on our own. After downloading the jfreechart package, there are already many examples, because jfreechart
There are very few documents used for this project, so the best way to learn it is to learn the example source code it carries. In the package
Org. jfree. Chart. Demo contains dozens of files used to display the results of all charts supported by jfreechart. If your JDK is
In newer cases, problems may occur when running these examples, as shown below:
Java. Lang. unsatisfiedlinkerror: initddraw
At sun. AWT. Windows. win32offscreensurfacedata. initddraw (native method)
At sun. AWT. Windows. win32offscreensurfacedata. (Win32offscreensurfacedata. Java: 141)
At sun. AWT. win32graphicsdevice. (Win32graphicsdevice. Java: 58)
At sun. AWT. win32graphicsenvironment. makescreendevice (win32graphicsenvironment. Java: 168)
At sun. java2d. sungraphicsenvironment. getscreendevices (sungraphicsenvironment. Java: 240)
At sun. AWT. win32graphicsenvironment. getdefascrescreendevice (win32graphicsenvironment. Java: 61)
At java. AWT. Window. INIT (window. Java: 224)
At java. AWT. Window. (Window. Java: 268)
At java. AWT. Frame. (Frame. Java: 398)
At javax. Swing. jframe. (Jframe. Java: 198)
At org. jfree. Chart. Demo. jfreechartdemo. (Jfreechartdemo.java: 148)
At org. jfree. Chart. Demo. jfreechartdemo. Main (jfreechartdemo. Java: 285)
Exception in thread "Main"
This error occurs because the new swing version uses Microsoft DirectDraw technology to improve the Drawing performance.
This technology is not supported by your mood or graphics card. Is there no way? To solve this problem
This problem is also very simple. We can block DirectDraw and prevent swing from using this technology. When running the code
Specify the parameter-dsun. java2d. noddraw for the VM.
At this time, you may be wondering again, not to mention the web-based chart. Why did it go to swing again? This is because to enable developers
This is easy to use and requires no running environment configuration. Therefore, these examples are presented to developers in Gui mode.
Charts. What we need to learn is how to use this engine to generate a chart instead of how to display a chart. When we generate
The chart object can be published on the Web by export to an image file.
The following describes several core object classes in jfreechart:
Class Name |
Class role and simple description |
Jfreechart |
A chart object. The final form of any type of chart is to customize some attributes of the object. The jfreechart engine provides a factory class for creating chart objects of different types. |
Xxxxxdataset |
A DataSet object that provides the data used to display charts. Different types of charts correspond to many types of DataSet object classes. |
Xxxxxplot |
The chart area object. Basically, this object determines the chart style. When creating this object, it must support axis, Renderer, and dataset objects. |
Xxxxxaxis |
The two axes used to process the chart: the vertical and horizontal axes. |
Xxxxxrenderer |
Displays a chart object. |
Xxxxxurlgenerator |
Used to generate the mouse click link for each project in the Web chart |
Xxxxxtooltipgenerator |
Help tips for generating images. Different types of charts correspond to different types of tooltip classes. |
Basically, I think the jfreechart project's class structure is not very well designed. First, a large number
Factory method. Although this can simplify the code for creating chart objects, it can be extended for the project itself or developers.
New types of charts are still very troublesome. Second, except for the chart object itself, other classes are too complex and users must
Understand which axis, plot, and Renderer classes should correspond to each type of chart object, and must be very familiar with the constructor of these classes.
The specific meaning of each parameter. These problems have plagued many beginners. However, although there are many problems, jfreechart
It is still a very good chart engine, and the project itself is gradually developing.
After a very brief introduction to the jfreechart code structure, let's start experimenting with several common charts and
Put it on the web.
3. Use jfreechart to generate charts of various styles
Due to space limitations, we only implement two commonly used charts here. Readers of other types of charts can bypass the category. Let's first give the column
And then 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 bar chart generation.
* @ Author winter Lau
*/
Public class barchartdemo {
Public static void main (string [] ARGs) throws ioexception {
Categorydataset dataset = getdataset2 ();
Jfreechart chart = chartfactory. createbarchart3d (
"Fruit yield Chart", // chart title
"Fruit", // The display label of the Directory axis
"Output", // display label of the numeric axis
Dataset, // Dataset
Plotorientation. Vertical, // chart direction: horizontal and vertical
True, // whether to display the legend (for a simple bar chart, it must be false)
False, // whether to generate a tool
False // whether to generate a URL link
);
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 ){}
}
}
/**
* Obtain a simple DataSet object for demonstration.
* @ Return
*/
Private Static categorydataset getdataset (){
Defaultcategorydataset dataset = new defaultcategorydataset ();
Dataset. addvalue (100, null, "apple ");
Dataset. addvalue (200, null, "Pears ");
Dataset. addvalue (300, null, "grape ");
Dataset. addvalue (400, null, "banana ");
Dataset. addvalue (500, null, "litchi ");
Return dataset;
}
/**
* Obtain a combined DataSet object for demonstration.
* @ 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", "Pears ");
Dataset. addvalue (200, "Shanghai", "Pears ");
Dataset. addvalue (200, "Guangzhou", "Pears ");
Dataset. addvalue (300, "Beijing", "grape ");
Dataset. addvalue (300, "Shanghai", "grape ");
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 effect of the image file generated after the program runs is as follows:
Figure 4
The following figure shows the image files generated when a simple data set is obtained using the getdataset method:
Figure 5
2 pie chart
For a pie chart, the dataset is not obtained using the same dataset class. In addition, the pie chart does not support sub-projects of the same category.
Project data. We only provide the code for creating a pie chart. As for writing a chart to a file, it is consistent with the column chart and does not need to be repeated.
Package lius. Chart. Demo;
Import java. Io .*;
Import org. jfree. Data .*;
Import org. jfree. Chart .*;
/**
* Shows how to generate a pie chart.
* @ Author winter Lau
*/
Public class piechartdemo {
Public static void main (string [] ARGs) throws ioexception {
Defaultpiedataset DATA = getdataset ();
Jfreechart chart = chartfactory. createpie3dchart ("fruit yield Chart", // chart title
Data,
True, // whether to display the legend
False,
False
);
// Write the chart object to the file and generate the source code by referencing the bar chart
}
/**
* Obtain a simple DataSet object for demonstration.
* @ Return
*/
Private Static defaultpiedataset getdataset (){
Defaultpiedataset dataset = new defaultpiedataset ();
Dataset. setvalue ("apple", 100 );
Dataset. setvalue ("Pears", 200 );
Dataset. setvalue ("grape", 300 );
Dataset. setvalue ("banana", 400 );
Dataset. setvalue ("litchi", 500 );
Return dataset;
}
}
The generated pie chart file has the following effects:
Figure 6
4. Move the generated chart to the browser
To directly transmit the generated chart to the client browser, you only need to replace the file stream in the previous two examples
The output stream obtained by the httpservletresponse object. The detailed code list is as follows:
Package lius. Chart. Demo;
Import java. Io. ioexception;
Import javax. servlet .*;
Import javax. servlet. http. httpservlet;
Import org. jfree. Data .*;
Import org. jfree. Chart .*;
/**
* Shows how to output charts directly through servlet.
* @ Author winter Lau
*/
Public class chartdemoservlet extends httpservlet {
Public void Service (servletrequest req, servletresponse res)
Throws servletexception, ioexception
{
Res. setcontenttype ("image/JPEG ");
Defaultpiedataset DATA = getdataset ();
Jfreechart chart = chartfactory. createpie3dchart ("fruit yield Chart ",
Data,
True,
False,
False
);
Chartutilities. writechartasjpeg (res. getoutputstream (),
100, chart, 400,300, null );
}
/**
* Obtain a simple DataSet object for demonstration.
* @ Return
*/
Private Static defaultpiedataset getdataset (){
Defaultpiedataset dataset = new defaultpiedataset ();
Dataset. setvalue ("apple", 100 );
Dataset. setvalue ("Pears", 200 );
Dataset. setvalue ("grape", 300 );
Dataset. setvalue ("banana", 400 );
Dataset. setvalue ("litchi", 500 );
Return dataset;
}
}
Advanced topic
In many cases, we not only need to display a chart in the browser, but also need customers to submit the chart directly.
Mutual operations, such as getting information prompts and clicking a part of the chart to display more details. For example, the preceding simple
Bar chart. You can click a fruit, for example, apple, to view the output of Apple in each region. Therefore
The image is required to have interactive operations. In HTML, to make an image interactive, you must specify
Defines a map object. The following table extracts an HTML code with this function.
Onclick = "javascript: clickchart ('20140901'); Return false;">
Onclick = "javascript: clickchart ('20140901'); Return false;">
Onclick = "javascript: clickchart ('20140901'); Return false;">
Onclick = "javascript: clickchart ('20140901'); Return false;">
Clickchart ('diet '); Return false; "shape = rect coords = 374,255, 17, href = "? Series = 0 & category = diet ">
This creates a problem: If a map object is generated based on an image. Let's look back at the code
There are two parameters when creating a chart object. In the example of a bar chart, the two parameters are chartfactory.
The last two parameters in the createbarchart3d method are boolean values. The two parameters mean: Yes
Whether to create a tooltip and generate a URL. The two parameters correspond to the title attribute and
Href attribute.
But what I want to know is how to generate this map! Haha, don't worry. jfreechart has helped us generate map pairs.
. To generate a map object, we need to introduce another object: chartrenderinginfo. Because jfreechart does not have direct
The method uses a chart object to directly generate map data. It requires an intermediate object for transition. This object is
Chartrenderinginfo. Is the flowchart for generating map data:
Figure 7
As shown in, the chartutilities class is the core of the entire process. Its surrounding objects are data objects or files.
This process is described as follows: first create a chartrenderinginfo object and call chartutilities's writechartasjpeg
Is passed as the last parameter. After this method is called, an image file and
Chartrenderinginfo object. With this object, we still have no way to obtain the specific map data.
The writeimagemap method of chartutilities is used to read the chartrenderinginfo object and obtain the code snippet of map data, as shown in figure
Below:
Printwriter W = NULL;
Fileoutputstream fos_jpg = NULL;
Fileoutputstream fos_cri = NULL;
Try {
// Use different classes based on different types of charts. The following operations are performed on pie charts:
Pieplot plot = (pieplot) Chart. getplot ();
Plot. seturlgenerator (New standardpieurlgenerator (URL ));
// Set the tooltip
Plot. settooltipgenerator (New standardpietooltipgenerator ());
Fos_jpg = new fileoutputstream ("D: // fruit.jpg ");
Chartutilities. writechartasjpeg (
Fos_jpg,
100,
Chart,
400,
300,
Info );
Fos_cri = new fileoutputstream (_ D: // fruit. Map __);
W = new printwriter (fos_cri );
Chartutilities. writeimagemap (W, _ mapname __, info );
W. Flush ();
} Finally {
Try {
W. Close ();
} Catch (exception e ){}
Try {
Fos_cri.close ();
} Catch (exception e ){}
Try {
Fos_jpg.close ();
} Catch (exception e ){}
}
Open the file D:/fruit. map. The content of the file is the map data to be written to the page. Generate image files and map data files
To complete the hotspot chart function. As for how to combine the relationship between the two, the usemap attribute value of the sample image must be
When combined with the map object name, it must be processed according to the actual application. I suggest using tags
Library encapsulation, the name of the image file and the name of the map object are controlled by the tag library in a unified manner, so that one of the two
.