Use JFreeChart to create a web-based chart

zhaozj2021-02-16  90

I. Introduction to the JFreeChart project

JFreeChart is a Java project on the open source site sourceforge.net, which is mainly used for a variety of charts, these pictures

Tables include: pie chart, histogram (ordinary histogram, stack column), line diagram, regional diagram, distribution map, mixed chart, Gantt chart,

Some instrument panels, etc. These different graphs can basically meet the current requirements. In order to reduce the space, this article mainly introduces the front

Three types of charts, readers can touch the class to develop charts of other styles. The following is the three types generated by JFreechart

The results of the chart:

figure 1

figure 2

image 3

The above three figures are the sales information of a certain product in four quarters. You must prepare the development ring before continuing the following section.

Premier, because it is a graphic display based on a web browser, there is a servlet engine or a J2EE application server (for example

WebSphere, Tomcat, etc.). The construction of the web environment is not cumbersome, and the reader is installed according to the preferences. JFreeChart Engine itself

Need to download the SourceForge.net, the address is as follows:

JFreeChart Home: http://www.jfree.org/jfreechart/index.htmljfreechart 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, interpret the source code structure of JFreeChart

We must first understand the structure of JFreeChart itself and some examples it belongs before starting to use JFreeChart.

The order, this helps us to develop it next steps. Download the JFreeChart package has already had a very rich example because JFreeChart

This project itself has very little document, so learning it is the best way to learn the example source code it belongs. In the package

There are dozens of files in Org.jfree.Chart.demo to show all the results of all charts that JFreeChart can support. If your JDK is better

In addition, there may be problems when running these examples, the phenomenon is as follows:

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.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 technique that uses Microsoft's DirectDraw technology to improve the performance of the drawing, and maybe you

The card will not support such an emotions or graphics cards at this time. Is there any way? To solve this

A problem is also very simple, we can block DirectDraw and do not let Swing use this technology. When running these code

Specify parameters to virtual machines - 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 in order to make developers

Easy to get started, there is no need to configure any operating environment, so these examples are based on the GUI mode for display to the developer if generated.

A chart, we have to learn how to use this engine to generate charts instead of how to display a chart. When we generate

Chart object export to an image file to be published 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 itself is not very good. First, you will use a lot of time when you create a chart.

Factory method, so although you can simplify the code of creating chart objects, you can expand your project itself or developers.

The new chart is still a very troublesome thing; secondly, in addition to the graphic object itself is too complicated, the user must go

Solution Each type of chart object should correspond to which Axis, Plot, Renderer class, and must be very familiar with these classes of constructor

The specific meaning of each parameter. These issues have greatly 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 very briefly introduced the code structure of JFreeChart itself, let's start trial a few common charts and put them.

Put it on the web.

Third, use JFreeChart to generate a variety of patterns

Issues that are limited to space We only achieve two common charts, other types of table readers can touch bypass. Let us give the column first

The implementation of the chart, the implementation of the pie chart is again compared.

1 column map

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 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 Diagram", // Chart Title "Fruit", // Directory axis display tag "Yield", // numeric axis display tag DataSet, // Data Set Plotorientation.vertical, // Chart Direction: Horizontal, Vertical True, / / ​​Whether to display the legend (for simple histogram must be false) false, // Does the tool false // generate URL links); fileOutputStream fos_jpg = NULL; tryoutputStream ("D: //fruit.jpg"); ChartUTILITIES.WRITECHARTASJPEG (FOS_JPG, 100, CHART, 400, 300, NULL);} finally {try {fos_jpg.close ();} catch (Exception e) {}}} / ** * Get a deliberate dataset of a demonstration * @Return * / private static categoryDataSet getDataSet () {defaultcategoryDataSet DataSet = new defaultcategoryDataSet (); Dataset.AddValue (100, null, "Apple" ); Dataset.addvalue (200, NULL, "pear"); Dataset.addValue (300, NULL, "Grape"); Dataset.AddValue (400, Null, "Banana"); Dataset.AddValue (500, null, " Lychee "); return dataset;} / ** * Get a combination of delta data set object * @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 "," Pears "); Dataset.addValue (200," Shanghai "," Pear "); Dataset.addValue (200," Guangzhou "," Pear "); 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", "lychee"); Return Dataset;} The image file generated after the end of the program runs, as shown below: Figure 4 If you are using simple data, it is used to obtain the image file generated when using the getDataSet method. : 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.Demo; import java.io. *; import org.jfree.data. *; import org.jfree.chart. *; / ** * The generation of the presentation 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 map", // chart title data, true, // whether the legend False, false); // Write chart object to file, refer to the column graph generation source code} / ** * Get a deliberate dataset object * @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 effect is as follows: Figure 6I, move the generated chart to the browser to pass the generated chart to the client browser, only need to The file streaming in two examples is the output stream acquired by the HTTPServletResponse object. The detailed code list is as follows: package lius.chart.deemo; import javax.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 Diagram", DATA, TRUE, FALSE, FALSE; Chartutilities.writeChartasjpeg (Res. GetoutputStream (), 100, Chart, 400, 300, NULL);} / ** * Get a simple data set for a demonstration Object * @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;}} Many cases of topics, we can not only display a chart on your browser, we need to do interacting operations directly on the chart, such as getting information prompts, click on a portion of the chart to make more details. For example, the simple histogram generated in front, the user needs to see some fruit production after seeing the histogram, for example, Apple can see the amount of 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 having a portable function, you must define a MAP object to the image. The following table exceeded the HTML code with this feature οnclick = "JavaScript: ClickChart ('100'); Return False;"> οnclick = "JavaScript: ClickChart ('200'); Return False;"> οnclick = "JavaScript: ClickChart ('300'); RETURN FALSE; "> οnclick =" JavaScript: ClickChart ('400'); Return False; "> Clickchart ('Diet'); Return False;" Shape = Rect Coords = 329, 17, 374, 255 href = " • SERIES = 0 & category = DIET "> The resulting problem: If you generate a corresponding MAP object according to an image. We look back at the code that just now, there are two parameters when creating a chart object, our cylindrical map Examples of these two parameters are the last two parameters in ChartFactory. CreateBarchart3D method, the types of these two parameters are Boolean. These two parameters are: whether to create tooltips (Tooltip) and whether to generate URLs These two parameters respectively correspond to a name attribute in Map and HREF attributes. But 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 Generating a map object to 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 of generating MAP data: As shown in the figure above, the ChartUTILITIES class is the core of the entire process. Its objects around it are some, such as data objects or files. This process is simple to describe the following: First create a ChartRenderingInfo object and call ChartUTILITIES's WriteChartasjpeg as the last A parameter is passed in.

转载请注明原文地址:https://www.9cbs.com/read-12813.html

New Post(0)