Liu Dong (Winter.lau@163.com) Software Engineer, Zhuhai, Iron Technology Development Co., Ltd. September 2003
The development of WWW makes the Internet-based application are no longer limited to static or simple dynamic content. Traditional some published applications, such as report systems, are gradually moved to the Internet. However, there is a difference between the two, although it is basically similar to data acquisition, business processing, etc., but the biggest difference is the user interface. In order to display the user interface to display data on a web browser, the user interface that uses the operating system itself can be developed by the user interface that uses the operating system itself to unable to adapt to the dazzling client, so it has become incompetent here. . Back to the topic of this article, in order to create a picture to see charts on a web browser: The first is to use the applet to use the Java itself to support graphic support to display a chart; the second is direct in Web The server is sent to the browser after generating a chart image file. The first way is obviously too high for the client. With the current mainstream browser gives up the support for Java, this method is only suitable for some local area network applications, and the environment for the Internet is not suitable. So we will introduce a Java chart engine JFreeChart to generate a web-based chart.
I. JFreeChart Project Introduction JFreeChart is a Java project on SourceForge.NET, which is open source site, which is mainly used to include: pie chart, histogram (ordinary column chart, and stack post chart), Line diagram, regional diagram, distribution map, mixed chart, Gantt chart, and some instrument panels, etc. These different graphs can basically meet the current requirements. In order to reduce the context, this paper mainly introduces the previous three types of charts, the reader can touch the graph to develop other styles. The following is the result of these three types of charts generated by JFreeChart:
figure 1
figure 2
image 3
The above three figures are the sales information of a certain product in four quarters. You must first prepare the development environment before proceeding with the following section, because it is a graphic display based on a web browser, so you need a servlet engine or a J2EE application server (such as WebSphere, Tomcat, etc.). The construction of the web environment is not cumbersome, and the reader is installed according to the preferences. The JFreeChart engine itself needs to be downloaded on the sourceforge.net, the address is as follows:
JFreechart Home: http://www.jfree.org/jfreechart/index.html
JFreeChart Download Page: http://sourceforge.net/projects/jfreechart/
When downloading, you need to pay attention to you must download two files: JFreeChart and JCommon. At present, the latest version is: jfreechart 0.9.11 JCommon 0.8.6
It is aware of the problem that I meet in the development. It should be noted that when using Eclipse development, it will report an inexplicable error, and the error may point to the first line of a class file. This problem is generally because there is no reason for the JCMMON's JAR package to the project's class path. Specific reasons are immune.
Second, interpretation of JFreeChart Structure Before starting using JFreeChart, we must first understand the structure of JFreeChart itself and some examples thereof, which helps us to develop next yourself. Downloading the JFreeChart package has already had a very rich example, because JFreeChart this project itself is very small, so learning it is the best way to learn the example source code it belongs. There are dozens of files in the package org.jfree.chart.demo to show all the results of all charts that JFreeChart can support. If your JDK is more new, there will be problems when running these examples, and the phenomenon is as follows:
Java.lang.unsatisfiedlinkerror: initdddrawat 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.com (Win32Graphicsenvironment (Win32Graphicsenvironment ).java: 168)
At sun.java2d.sungraphicsenvironment.getscreenDevices (Sungraphicsenvironment.java:240)
At sun.awt.win32graphicsenvironment.getdefaultscreenDevice (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 is due to the new version of Swing's large number of technologies that use Microsoft DirectDraw technology to improve the performance of the drawing, and you may have a technique that you will not support you at this time. Is there any way? It is also very simple to solve this problem. We can block DirectDraw, and you can use this technology without swing. Specify parameters to the virtual machine when running these code - DSun.java2d.noddraw.
At this time, you may be wondering again, don't say it is a web-based chart, how can I pull Swing? This is because the developers are easy to get started without configuring any operating environment, so these examples are based on the GUI mode for display to the developer if they have to generate a chart, how do we learn how to use this engine to generate a chart instead of How to display a chart. When we use the generated chart object export to an image file to be released on the web.
Let's introduce several core objects in JFreechart:
The role of the class name class and the simple description of the JFreeChart chart object, and the final expression of any type of chart is customized in this object. The JFreeChart engine itself provides a factory class for creating different types of chart object XXXXDataSet dataset objects for providing data used in the chart. According to different types of charts, there should be many types of dataset object class XXXXXPLOT chart area objects. Basically this object determines what styles of charts. When you create this object, you need AXIS, RENDERER, and data set objects to support XXXXXAXIS for processing charts. Two axes: longitudinal axis and horizontal axis xxxxrenderer How to display a chart object XXXXXURLGENERATOR to generate a mouse for each project in a web chart Click the link XXXXTooltipGenerator to generate a help prompt for image, different types of charts correspond to different types of tool tips. class
Basically I think the design of the class structure of the JFreeChart project is not very good. First, use a large number of factory methods when creating charts, so although it can simplify the code of the chart object, but for the project itself or developers It is still a very troublesome thing to extend a new chart; secondly, in addition to chart object itself, the user must know which Axis, Plot, Renderer class, which must know each type of chart object. And you must be very familiar with the specific meaning of each parameter in these classes. These issues have greatly plagued many beginners. However, although there are many problems, JFreeChart itself is still a very good chart engine, and the project itself is gradually developing. After very briefly introduced the code structure of JFreeChart itself, let's start trial a few common charts and put them on the web.
Third, using JFreeChart to generate various styles of charts to the problem of space, we only achieve two common charts here, other types of chart readers can touch bypass. We first give the cosmication map, and the achievement of the pie chart is again compared.
1 column map
Package Lius.Chart.de;
Import java.io. *;
Import org.jfree.data. *;
Import Org.jfree.Chart. *;
Import Org.jfree.Chart.plot. *;
/ **
* This class is used to demonstrate the simplest histogram generation
* @Author Winter Lau
* /
Public class barchartdemo {
Public static void main (string [] args) throws oException {
CategoryDataSet DataSet = getDataSet2 ();
JFreeChart Chart = ChartFactory.createBarchart3d (
"Fruit Yield Chart", // Chart Title
"Fruit", // directory axis display tag
"Yield", // numeric axis display tag
DataSet, // Dataset
Plotorientation.Vertical, // Chart direction: horizontal, vertical
True, / / Whether the legend (for simple histogram must be false)
FALSE, / / Do you generate a tool
False // Do you 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) {}
}
}
/ **
* Get a simple dataset object with a demonstration
* @Return
* /
Private static categoryDataSet getDataSet () {
DefaultcategoryDataSet DataSet = New Default ();
DataSet.AddValue (100, NULL, "Apple");
Dataset.addValue (200, NULL, "Pear");
Dataset.addValue (300, NULL, "Grape");
Dataset.addValue (400, NULL, "Banana");
Dataset.addValue (500, NULL, "Litchi");
Return DataSet;
}
/ **
* Get a combined dataset object with a demonstration
* @Return
* /
Private static categoryDataSet getDataSet2 () {
DefaultcategoryDataSet DataSet = New Default ();
Dataset.addValue (100, "Beijing", "Apple");
DataSet.addValue (100, "Shanghai", "Apple");
Dataset.addValue (100, "Guangzhou", "Apple");
Dataset.addValue (200, "Beijing", "Peer");
Dataset.addValue (200, "Shanghai", "Peer");
DataSet.addValue (200, "Guangzhou", "Peer");
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 image file generated after the program is running, as shown below:
Figure 4
If you are using simple data, you can use the getDataSet method to get the data set as follows:
Figure 5
2 pie chart
For pie charts, the acquisition of the data set is not the same data set, and the other pie chart does not support data such as subjects in the same category. We only give the code that created the pie chart, as for the graph to a file, consistent with the histogram without repeating.
Package Lius.Chart.de;
Import java.io. *;
Import org.jfree.data. *;
Import Org.jfree.Chart. *;
/ **
* Used to present the generation of pie chart
* @Author Winter Lau
* /
Public class piechartdemo {
Public static void main (string [] args) throws oException {
DEFAULTPIEDATASET DATA = getDataSet ();
JFreechart chart = chartfactory.createpie3dchart ("Fruit Yield Diagram", // Chart Title
Data,
True, // Whether to display the legend
False,
False
);
// Write a chart object to the file, refer to the histogram generation source code
}
/ **
* Get a simple dataset object with a 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 is as follows:
Figure 6
Fourth, move the generated chart to the browser to pass the generated chart to the client browser, just need to stream the file in the previous two examples into the output stream acquired by the HTTPSERVLETRESPONSE object, detailed code list as follows:
Package Lius.Chart.de;
Import java.io.ioException;
Import javax.servlet. *;
Import javax.servlet.http.httpservlet;
Import org.jfree.data. *;
Import Org.jfree.Chart. *;
/ **
* Direct output chart 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 Production Map",
Data,
True,
False,
False
);
Chartutilities.writechartasjpeg (res. GetOutputStream (),
100, CHART, 400, 300, NULL);
}
/ **
* Get a simple dataset object with a 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 topics There are many cases, we need to display a chart on your browser, we need to do interacting operations directly on the chart, such as getting information prompts, click on a part of the chart to make more details, etc. . For example, the simple column chart of the previously generated, the user needs to see some fruits after seeing the histogram, for example, Apple can see the apple production in each region. This graphic is required to have an interactive function for this purpose. In HTML, in order to make an image have a function of interactive, you must define a MAP object. The following table excerpts an HTML code with this feature
This creates a problem: if a corresponding MAP object is generated according to an image. Let's look back at the code just now, there are two parameters when you create a chart object, and our examples of the column maps are the last two parameters in ChartFactory. Createbarchart3D method, these two parameters type It is a Boolean value. These two parameters means: whether to create a tooltip (Tooltip) and whether the URL is generated. These two parameters respectively correspond to a Title attribute of an area in MAP and the HREF attribute. But what I want to know how to generate this map! Haha, don't worry, JFreeChart has helped us do a good job in generating MAP objects. In order to generate a MAP object, you will introduce another object: ChartRenderingInfo. Because JFreeChart does not have a direct method to generate MAP data with a chart object, it requires an intermediate object to transition, this object is ChartRenderingInfo. The following figure is a flow chart for generating MAP data:
Figure 7
As shown in the figure above, the ChartUTILITIES class is the core of the entire process, and the object around it is some, such as data objects or files. This process is briefly described as follows: First, create a ChartRenderingInfo object and transfer it to the last parameter when calling ChartUTILITIS WriteChartasJPEG. When calling this method, an image file and a ChartRenderingInfo object that fills MAP data will be generated. We have no way to obtain specific MAP data, we must also read the ChartRenderingInfo object by means of the WriteImageMap method of ChartUTILITIES. The code segment for getting MAP data is as follows:
PrintWriter W = NULL;
FileOutputStream FOS_JPG = NULL;
FileOutputStream FOS_CRI = NULL;
Try {
/ / Use different classes according to different types of charts, the following is the operation of the pie chart
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 to write MAP data on the page. Write the generated image file and the MAP data file to the page to complete the functionality of the hotspot chart. As for how to combine the relationship between the two, for example, the USEMAP attribute value of the image must be combined with the name of the MAP object, the corresponding processing must be performed according to the actual application. The author suggested that both the two passed the label library, the name of the image file, and the name of the MAP object was controlled by the label library, so that the consistency of the two can be guaranteed. Reference
JFreeChart chart engine home CEWOLF Custom Chart Tag Library
About the author Liu Dong, he is no longer called the canned pineapple. Zhuhai City, ICS, software engineers, mainly engaged in the development of commercial intelligence (BI) on the J2EE platform. Contact number: 0756-3377435-383 Email: winter.lau@163.com