Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are several ways for JfreeChart to generate pictures?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are several ways for JfreeChart to generate pictures? for this question, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Here are several ways for JfreeChart to generate pictures.

Let's find some introductions from the Internet.

I. brief introduction

With the development of WW, Internet-based applications are no longer limited to static or simple dynamic content delivery. Some traditional applications released in the form of software packages, such as reporting systems, are gradually moving to the Internet. However, there is a big difference between the two. Although they are basically similar in terms of data acquisition and business processing, the difference lies in the user interface. In order to display on the web browser, the user interface is required to use HTML and pictures to show the data, while the traditional user interface developed by using the controls of the operating system itself can not adapt to the dazzling array of clients, so there is nothing we can do here. Coming back to the title of this article, there are generally two ways to create a chart that can be viewed on a web browser: * is to use applet to display a chart using java's own support for graphics; the second is to directly generate a chart image file on the web server and send it to the browser. * this method is obviously too demanding for the client. With the current mainstream browsers giving up support for JAVA, this method is only suitable for some LAN applications, but not suitable for the Internet environment. So we will introduce a JAVA chart engine JFreeChart to generate WEB-based charts.

JFreeChart Project profile JFreeChart is an JAVA project on the open source site SourceForge.net, which is mainly used for a variety of charts, including: pie chart, bar chart (universal bar chart and stack bar chart), line chart, area chart, distribution chart, mixed chart, Gantt chart and some dashboards and so on. These different styles of charts can basically meet the current requirements.

II. JFreeChart acquisition

JFreeChart is a project of JFreeChart on the open source website SourceForge.net. The company's main products are as follows:

1.JFreeReport: report solving tool

2.JFreeChart:Java Graphics solution (Application/Applet/Servlet/Jsp)

3.JCommon: common class libraries for JFreeReport and JFreeChart

4.JFreeDesigner: report Design tool of JFreeReport

We can get the * * version and related materials from jfree's official website (but jfree's document costs $40)

Get the address: http://www.jfree.org/jfreechart/index.html (you can also get a brief introduction)

Let's take the current * * version: jfreechart-1.0.1.zip as an example.

III. JFreeChart configuration and installation

1, extract jfreechart-1.0.1.zip.zip to the specified location, where source is the source code of jfreechart, jfreechart-1.0.1-demo.jar is the example program, you can first run to see a variety of effects, you will know his nb.

2. In order to successfully configure, we need to pay attention to the following three files:

Set up the classpath. Add the following three jar packages.

Jfreechart-1.0.1.jar 、 jcommon-1.0.0.jar 、 gnujaxp.jar

Plus the third jar package, sometimes web.xml will report an error, just get rid of it.

At this point, the configuration of jfreechart is complete, and now you are ready for jfreechart development. What is worth mentioning here is that the compatibility of jfreechart class structure before and after design is not very good. The class library structure may be different in different versions of jfreechart, and sometimes you may need to check the source code. If it is displayed in Chinese, you may need to change the font of the source code according to the look and feel.

IV. Introduction of JFreeChart function

JFreeChart is currently a * java graphics solution, which can basically meet the current graphics needs, including the following aspects:

Pie charts (2D and 3D): pie chart (planar and stereoscopic)

Bar charts (regular and stacked, with an optional 3D effect): bar chart

Line and area charts: graphs

Scatter plots and bubble charts

Time series, high/low/open/close charts and candle stick charts: sequence diagram

Combination charts: composite diagram

Pareto charts

Gantt charts: Gantt Chart

Wind plots, meter charts and symbol charts

Wafer map charts

(state chart, pie chart (2D and 3D), bar chart (horizontal, vertical), line chart, dot chart, time change chart, Gantt chart, stock market chart, mixed chart, thermometer chart, scale chart and other common commercial charts)

Drawings can be exported to PNG and JPEG formats, and can also be associated with PDF and EXCEL

Introduction to the JFreeChart core class library:

Study of jfreechart source code found that the source code is mainly composed of two large packages: org.jfree.chart,org.jfree.data. The former is mainly related to the graphics itself, while the latter is related to the data displayed by the graphics. If you are interested in the specific research, you can study it yourself.

The main core classes are:

Org.jfree.chart.JFreeChart: chart object, the final representation of any type of chart is to customize some properties in this object. The JFreeChart engine itself provides a factory class for creating different types of chart objects

Org.jfree.data.category.XXXDataSet: a dataset object that provides the data used to display the chart. According to different types of charts, there are many types of dataset object classes.

Org.jfree.chart.plot.XXXPlot: chart area object, which basically determines what kind of chart. When creating this object, you need the support of Axis, Renderer and dataset objects.

Org.jfree.chart.axis.XXXAxis: two axes for working with charts: vertical axis and horizontal axis

Org.jfree.chart.render.XXXRender: responsible for how to display a chart object

Org.jfree.chart.urls.XXXURLGenerator: mouse-click links used to generate each item in the Web diagram

XXXXXToolTipGenerator: help tips for generating images. Different types of charts correspond to different types of tooltip classes.

Personally, I feel that JFreeChart can meet the needs of most picture creation, but the only drawback is that the font setting is not good enough, especially when using Chinese. For this reason, it is recommended that you modify his source code and use the properties file to set the font. Also, the documentation costs money, so spend more time looking at the source code. Or go to the community more.

Five. start development

After having a preliminary understanding of JfreeChart and making preparations, we began to experiment with the example program. Here I only introduce the method of pie chart, and this picture is output in different ways, other types of pictures can refer to the examples provided by jfreechart, the practice is similar.

1. Generate pictures directly

Public class PieChartPicture {public static void main (String [] args) {PieDataset dataset = getDataSet (); JFreeChart chart = ChartFactory.createPieChart3D ("Project schedule Distribution", / / chart title dataset,// data true,// include legend true, false); PiePlot3D plot= (PiePlot3D) chart.getPlot () / / percentage displayed in the picture: default method / / plot.setLabelGenerator (new StandardPieSectionLabelGenerator (StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT)) / / percentage displayed in the picture: custom mode, {0} indicates option, {1} indicates numeric value, {2} represents percentage, two places after decimal point plot.setLabelGenerator (new StandardPieSectionLabelGenerator ("{0} = {1} ({2})", NumberFormat.getNumberInstance (), new DecimalFormat ("0.00%") / / percentage of legend display: custom mode, {0} indicates option, {1} indicates numeric value, {2} represents percentage plot.setLegendLabelGenerator (new StandardPieSectionLabelGenerator ("{0} = {1} ({2})")); / / sets background color to white chart.setBackgroundPaint (Color.white) / / specify the transparency of the picture (0.01.0) plot.setForegroundAlpha (1.0f); / / specify the circle (false) and ellipse (true) plot.setCircular (true) on the pie chart displayed; / / set the font of the chart title Font font = new Font ("boldface", Font.CENTER_BASELINE,20); TextTitle title = new TextTitle ("Project status Distribution"); title.setFont (font) Chart.setTitle (title); FileOutputStream fos_jpg= null; try {fos_jpg=new FileOutputStream ("D:\\ project status distribution .jpg"); ChartUtilities.writeChartAsJPEG (fos_jpg,100,chart,640,480,null); fos_jpg.close ();} catch (Exception e) {}} private static PieDataset getDataSet () {DefaultPieDataset dataset = new DefaultPieDataset () Dataset.setValue ("pre-Market", new Double (10)); dataset.setValue ("Project", new Double (15)); dataset.setValue ("Plan", new Double (10)); dataset.setValue ("requirements and Design", new Double (10)); dataset.setValue ("Executive Control", new Double (35)); dataset.setValue ("closure", new Double (10)) Dataset.setValue ("operation and maintenance", new Double (10)); return dataset;}

2. Output with action mode of servlet and struts

Output in this way, no need to generate pictures.

1) servlet output

Public class PieByServlet extends HttpServlet {public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException {res.setContentType ("image/jpeg"); PieDataset dataset = getDataSet (); JFreeChart chart = ChartFactory.createPieChart3D ("fruit pie chart", / / chart title dataset,// data true, / / include legend true, false) / / set the chart properties / / output the picture ChartUtilities.writeChartAsJPEG (res.getOutputStream (), 100memeChartPerson800Phont600Null);}

2) action output of struts

Just add this statement to try catch and return null.

Try {ChartUtilities.writeChartAsJPEG (response.getOutputStream (), 100 catch ChartQuery 800, 600);} catch (chartje) {} return null

In fact, the use of these two methods does not change much with the way of generating pictures.

Add the statement response.setContentType ("image/jpeg")

ChartUtilities.writeChartAsJPEG (new FileOutputStream ("D:\\ project status distribution .jpg");, 100memeChartRecention640and480nulls)

Just change the file stream to the output stream of response.

HartUtilities.writeChartAsJPEG (response.getOutputStream (), 100 chartchart800 800 600 null)

3. Jsp+servlet+javabean mode

1) Create ChartViewer servlet

Public class ChartViewer extends HttpServlet {public void init () throws ServletException {} / / Process the HTTP Get request public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/ / get the chart from session HttpSession session = request.getSession (); BufferedImage chartImage = (BufferedImage) session.getAttribute ("chartImage"); / / set the content type so the browser can see this as a picture response.setContentType ("image/png"); / / send the picture PngEncoder encoder = new PngEncoder (chartImage, false, 0,9) Response.getOutputStream (). Write (encoder.pngEncode ());} / / Process the HTTP Post request public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);} / / Process the HTTP Put request public void doPut (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} / / Clean up resources public void destroy () {}

2) Create a servlet map in web.xml

ChartViewer myapp.webwork.servlets.ChartViewer ChartViewer / servlet/ChartViewer

3) Create a chart in a java bean (Pie3DDemo.java)

Public class Pie3DDemo {private DefaultPieDataset getDataset () {/ / categories... String [] section = new String [] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; / / data... Double [] data = new double [section.length]; for (int I = 0; I

< data.length; i++) { data[i] = 10 + (Math.random() * 10); } // create the dataset... DefaultPieDataset dataset = new DefaultPieDataset(); for (int i = 0; i < data.length; i++) { dataset.setValue(section[i], data[i]); } return dataset; } public String getChartViewer(HttpServletRequest request, HttpServletResponse response) { DefaultPieDataset dataset = getDataset(); // create the chart... JFreeChart chart = ChartFactory.createPie3DChart( "Pie3D Chart Demo", // chart title dataset, // data true, // include legend true, false ); // set the background color for the chart... chart.setBackgroundPaint(Color.cyan); PiePlot plot = (PiePlot) chart.getPlot(); plot.setNoDataMessage("No data available"); // set drilldown capability... plot.setURLGenerator(new StandardPieURLGenerator("Bar3DDemo.jsp","section")); plot.setLabelGenerator(null); // OPTIONAL CUSTOMISATION COMPLETED. ChartRenderingInfo info = null; HttpSession session = request.getSession(); try { //Create RenderingInfo object response.setContentType("text/html"); info = new ChartRenderingInfo(new StandardEntityCollection()); BufferedImage chartImage = chart.createBufferedImage(640, 400, info); // putting chart as BufferedImage in session, // thus making it available for the image reading action Action. session.setAttribute("chartImage", chartImage); PrintWriter writer = new PrintWriter(response.getWriter()); ChartUtilities.writeImageMap(writer, "imageMap", info); writer.flush(); } catch (Exception e) { } String pathInfo = "http://"; pathInfo += request.getServerName(); int port = request.getServerPort(); pathInfo += ":"+String.valueOf(port); pathInfo += request.getContextPath(); String chartViewer = pathInfo + "/servlet/ChartViewer"; return chartViewer; } 4)页面 Pie Chart Demo Pie Chart Demo

4. Use tool class ChartUtil and DisplayChart (servlet of jfreechart) output

I used the above methods to output pictures and found that only one picture can be output on the page, but the following method can output multiple pictures, and it is the simplest of several ways, which is recommended.

This method is similar to the above three, is to write the method of generating pictures in javabean into a tool class ChartUtil.

1) add tool class ChartUtil

Public class ChartUtil {

/ / generate a time series diagram and return the name of the picture

Public static String generatePieChart (DefaultPieDataset dataset,String title,int width,int height,HttpSession session, PrintWriter pw) {String filename = null; try {if (session! = null) {ChartDeleter deleter = (ChartDeleter) session.getAttribute ("JFreeChart_Deleter"); session.removeAttribute ("JFreeChart_Deleter"); session.setAttribute ("JFreeChart_Deleter", deleter) } JFreeChart chart = ChartFactory.createPieChart3D (title, / / chart title dataset, / / data true, / / include legend true, false); / / Write the chart image to the temporary directory ChartRenderingInfo info = new ChartRenderingInfo (new StandardEntityCollection ()); / / If the last parameter is null, the chart is a "one time"-chart and will be deleted after the first serving. / / If the last parameter is a session object, the chart remains until session time out. Filename = ServletUtilities.saveChartAsPNG (chart, width, height, info, session); / / Write the image map to the PrintWriter ChartUtilities.writeImageMap (pw, filename, info,true); pw.flush ();} catch (Exception e) {System.out.println ("Exception -" + e.toString ()); e.printStackTrace (System.out); filename = "picture_error.png";} return filename;}}

2) Statistics the data in action and set the dataset dataset. Upload to the page

3) take it out of the page

DefaultPieDataset piedataset= (DefaultPieDataset) request.getAttribute ("piedataset")

/ / use ChartUtil tool class to generate pictures

String p = ChartUtil.generatePieChart (piedataset, "Project Revenue and Expenditure Chart", 500, 300, null, new PrintWriter (out)); String p1 = request.getContextPath () + "/ servlet/DisplayChart?filename=" + p

Output in the following ways

4) add to web.xml

DisplayChart org.jfree.chart.servlet.DisplayChart DisplayChart / servlet/DisplayChart

5. PplicationFrame mode

Public class PieChartDemo1 extends ApplicationFrame {public PieChartDemo1 (String title) {super (title); setContentPane (createDemoPanel ());} private static JFreeChart createChart (PieDataset dataset) {JFreeChart chart = ChartFactory.createPieChart (. Return chart;} public static JPanel createDemoPanel () {JFreeChart chart = createChart (createDataset ()); return new ChartPanel (chart);} public static void main (String [] args) {PieChartDemo1 demo = new PieChartDemo1 ("PieChartDemo1"); demo.pack (); RefineryUtilities.centerFrameOnScreen (demo); demo.setVisible (true) }} the answers to the questions about how JfreeChart generates pictures are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report