SlideShare una empresa de Scribd logo
1 de 19
Creating Dynamic Charts With JFreeChart
 By David Keener
    www.keenertech.com



                         Copyright 2007 David Keener All rights reserved.
Overview
JFreeChart is an open source charting package implemented in Java. The
focus of this presentation is on using JFreeChart to embed charts within
web pages. After this presentation, you will be able to answer the following
questions about this exciting technology:

          • What is JFreeChart?
          • Why would you want to use it?
          • What do you need to use it?
          • Where do you get it?
          • How can charts be embedded in Java-based
            web pages?
          • What if your web site isn’t Java-based?
What Is JFreeChart?
•   Open source Java charting class library
•   Easy to use; with well-documented API
•   Supports dozens of chart types
•   Real-time chart generation
•   Extensive customization of charts
•   Can output charts in numerous formats
•   Mature technology – supported and
    enhanced since 2000
A Typical Chart
Supported Chart Types
•   Pie Charts            •   Line Charts
•   Exploded Pie Charts   •   Bar Charts
•   Area Charts           •   Layered Bar Charts
•   Stacked Area Charts   •   Stacked Bar Charts
•   Candlestick Charts    •   Statistical Bar Charts
•   Time Series Charts    •   Waterfall Charts
•   Gantt Charts          •   Meter Charts
•   Dual Axis Charts      •   Ring Charts
•   Histograms            •   Scatter Plots
•   Time Series Charts    •   Etc.
Prerequisites for Use
• Java 2 Platform (JDK 1.3 or later)
• JFreeChart 1.0.4 (as of February 9, 2007)
• (Optional) Web Container, e.g. – Tomcat,
  WebLogic, etc.
Where Do You Get It?
JFreeChart Home Page
  - http://www.jfree.org/jfreechart/


JFreeChart Documentation
• Free Installation Manual (PDF)
• Generated API Documentation
  - http://www.jfree.org/jfreechart/api/gjdoc/index.html

• Developer Manual (PDF)
  - Costs $48.75 for PDF download (well worth it!)
Ways to Produce Charts
JFreeChart is flexible enough to support a
 variety of ways to generate charts:

• Servlet
• Application
• Applet

For embedding charts within web sites,
servlets are generally used.
Servlet Review
To create a servlet, perform these steps:

• Create a class that extends the
  HttpServlet class
• Provide an implementation for either the
  doGet() or doPost() methods
• This method will produce the output that
  will be sent back to the requester
The Basic Servlet
import   java.io.IOException;         // Required Servlet Imports
import   java.io.OutputStream;
import   javax.servlet.*;
import   javax.servlet.http.*;

import   java.awt.Color;               // Imports related to chart production
import   org.jfree.chart.ChartFactory;
import   org.jfree.chart.ChartUtilities;
import   org.jfree.chart.JFreeChart;
import   org.jfree.data.general.DefaultPieDataset;

public class ChartServlet extends HttpServlet {

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
     throws IOException, ServletException {
     doTestPieChart(request, response);         // Will produce chart
  } // End Method

} // End Class
Steps to Produce a Chart
• Determine type of chart to be produced
• Get the raw data for the chart
• Store data in JFreeChart Dataset object
• Create a Chart object – Of desired chart
  type and passing in the Dataset object
• Customize Chart object as needed
• Output generated chart in desired format
Creating a Chart
protected void doTestPieChart(HttpServletRequest request,
   HttpServletResponse response) throws IOException, ServletException   {
     OutputStream out = response.getOutputStream();

    try     {
          DefaultPieDataset dataset = new DefaultPieDataset();

          dataset.setValue("Graphic Novels", 192);
          . . .

          JFreeChart chart = ChartFactory.createPieChart("Books by Type",
             dataset, true, false, false);
          chart.setBackgroundPaint(Color.white);      // Customize chart

          response.setContentType("image/png");
          ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
    }
    catch (Exception e) {
       System.out.println(e.toString());
    }
    finally {
       out.close();
    }
 } // End Method
Key Code Elements
dataset.setValue("Graphic Novels", 192);
. . .

JFreeChart chart = ChartFactory.createPieChart("Books by Type",
   dataset, true, false, false);




• Sets chart data items in a Dataset object
  (only one data line is shown)
• Creates a chart with a title, a dataset and
  flags
• Flags are: Yes for a legend, no for URLs
  and Tool Tips
Key Code Elements 2
OutputStream out = response.getOutputStream();

. . .

response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);



• Gets output stream from Response
• Sets mime type to “image/png”
• Uses ChartUtilities class to write the chart
  out as a PNG
• Writes the chart to the stream
• Chart is never stored as a file
Using the Servlet
• References servlet with URL like this:
 http://www.site.com/servlet/ChartServlet

• Servlet shows chart as an image
• Not embedded within a web page…

• How do you embed it within a web page?
Embedding a Chart
<html>
<head>
   <title>Test Chart</title>
</head>
<body>

<div align=center>
<img src=“/servlet/ChartServlet” width=400 height=300 border=0>
</div>

</body>
</html>



 • Uses a standard HTML IMG tag
 • The Tag references the chart servlet
 • Page loads; slight delay until chart shows
Referencing the Servlet
• Servlet can be referenced from anywhere
• Nothing in embedding technique requires
  Java except the servlet itself
• Non-Java sites can reference the servlet
• Servlet can function as sort of a “poor
  man’s web service”
• May need security for servlet to control
  where/how servlet is referenced
Other Ways to Use JFreeChart
• ChartUtilities class allows charts to be
  output in many formats, written to files,
  written to streams, etc.
• Charts can easily be incorporated into
  servlets (as just shown), or applets or
  applications
Summary
The benefits of JFreeChart are:

•   Dynamic generation of very nice charts
•   Easy integration into web sites
•   Light-weight, with few dependencies
•   Flexible usage; easily customizable
•   Numerous chart types
•   Numerous ways to output charts

Más contenido relacionado

La actualidad más candente

What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!scalaconfjp
 
DynamicRecord Presentation
DynamicRecord PresentationDynamicRecord Presentation
DynamicRecord Presentationlinoj
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングscalaconfjp
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRubyelliando dias
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryTomer Gabel
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesBrett Meyer
 
Shootout! template engines on the jvm
Shootout! template engines on the jvmShootout! template engines on the jvm
Shootout! template engines on the jvmNLJUG
 
Shootout! Template engines for the JVM
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVMJeroen Reijn
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeAndrus Adamchik
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_kIBM
 
Designing and Testing Accumulo Iterators
Designing and Testing Accumulo IteratorsDesigning and Testing Accumulo Iterators
Designing and Testing Accumulo IteratorsJosh Elser
 
Web development basics (Part-7)
Web development basics (Part-7)Web development basics (Part-7)
Web development basics (Part-7)Rajat Pratap Singh
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Matthew Barlocker
 

La actualidad más candente (20)

Synthetic models
Synthetic modelsSynthetic models
Synthetic models
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
DynamicRecord Presentation
DynamicRecord PresentationDynamicRecord Presentation
DynamicRecord Presentation
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
 
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and CapabilitiesNot Just ORM: Powerful Hibernate ORM Features and Capabilities
Not Just ORM: Powerful Hibernate ORM Features and Capabilities
 
Shootout! template engines on the jvm
Shootout! template engines on the jvmShootout! template engines on the jvm
Shootout! template engines on the jvm
 
Shootout! Template engines for the JVM
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVM
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Apache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM AlternativeApache Cayenne: a Java ORM Alternative
Apache Cayenne: a Java ORM Alternative
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k
 
Designing and Testing Accumulo Iterators
Designing and Testing Accumulo IteratorsDesigning and Testing Accumulo Iterators
Designing and Testing Accumulo Iterators
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Initializing arrays
Initializing arraysInitializing arrays
Initializing arrays
 
Web development basics (Part-7)
Web development basics (Part-7)Web development basics (Part-7)
Web development basics (Part-7)
 
Open Platform for AI & ML modeling
Open Platform for AI & ML modelingOpen Platform for AI & ML modeling
Open Platform for AI & ML modeling
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 

Destacado

Building University Websites with the Drupal Content Management System
Building University Websites with the Drupal Content Management SystemBuilding University Websites with the Drupal Content Management System
Building University Websites with the Drupal Content Management SystemMark Jarrell
 
Text mining and analytics v6 - p2
Text mining and analytics   v6 - p2Text mining and analytics   v6 - p2
Text mining and analytics v6 - p2Dave King
 
How to Become an Effective Front-line Manager?
How to Become an Effective Front-line Manager?How to Become an Effective Front-line Manager?
How to Become an Effective Front-line Manager?Anup Soans
 
File 118
File 118File 118
File 118okahata
 
умножение 3
умножение  3умножение  3
умножение 3guestddbae10
 
Rm 07-v1
Rm 07-v1Rm 07-v1
Rm 07-v1tomkacy
 
Lcwebinar rise of-the_databrarian_73961
Lcwebinar rise of-the_databrarian_73961Lcwebinar rise of-the_databrarian_73961
Lcwebinar rise of-the_databrarian_73961Sigaard
 
Bitter Pill: Why Medical Costs Are Killing Us?
Bitter Pill: Why Medical Costs Are Killing Us?Bitter Pill: Why Medical Costs Are Killing Us?
Bitter Pill: Why Medical Costs Are Killing Us?Anup Soans
 
Amical 2013 wksp multimodal projects for 21st century learning
Amical 2013 wksp multimodal projects for 21st century learningAmical 2013 wksp multimodal projects for 21st century learning
Amical 2013 wksp multimodal projects for 21st century learningHoda Mostafa
 
Panelinstr
PanelinstrPanelinstr
Panelinstrskatelal
 
Corridade Toros[1]
Corridade Toros[1]Corridade Toros[1]
Corridade Toros[1]jmgfiel
 
Setmana D’Activitats ExtraordinàRies
Setmana D’Activitats ExtraordinàRiesSetmana D’Activitats ExtraordinàRies
Setmana D’Activitats ExtraordinàRiesbertafv
 
земляная смесь
земляная смесьземляная смесь
земляная смесьfarcrys
 
Panelinstrph
PanelinstrphPanelinstrph
Panelinstrphskatelal
 
SheSpeaks Social Media Infographic
SheSpeaks Social Media InfographicSheSpeaks Social Media Infographic
SheSpeaks Social Media InfographicSheSpeaks Inc.
 
How to Search Thai Digital Database
How to Search Thai Digital DatabaseHow to Search Thai Digital Database
How to Search Thai Digital DatabaseGritiga Soothorn
 
October 2010
October 2010October 2010
October 2010hollsterm
 
How Firefox Works
How Firefox WorksHow Firefox Works
How Firefox Worksyuyatamaru
 

Destacado (20)

Building University Websites with the Drupal Content Management System
Building University Websites with the Drupal Content Management SystemBuilding University Websites with the Drupal Content Management System
Building University Websites with the Drupal Content Management System
 
Text mining and analytics v6 - p2
Text mining and analytics   v6 - p2Text mining and analytics   v6 - p2
Text mining and analytics v6 - p2
 
How to Become an Effective Front-line Manager?
How to Become an Effective Front-line Manager?How to Become an Effective Front-line Manager?
How to Become an Effective Front-line Manager?
 
File 118
File 118File 118
File 118
 
умножение 3
умножение  3умножение  3
умножение 3
 
Rm 07-v1
Rm 07-v1Rm 07-v1
Rm 07-v1
 
Lcwebinar rise of-the_databrarian_73961
Lcwebinar rise of-the_databrarian_73961Lcwebinar rise of-the_databrarian_73961
Lcwebinar rise of-the_databrarian_73961
 
Bitter Pill: Why Medical Costs Are Killing Us?
Bitter Pill: Why Medical Costs Are Killing Us?Bitter Pill: Why Medical Costs Are Killing Us?
Bitter Pill: Why Medical Costs Are Killing Us?
 
Amical 2013 wksp multimodal projects for 21st century learning
Amical 2013 wksp multimodal projects for 21st century learningAmical 2013 wksp multimodal projects for 21st century learning
Amical 2013 wksp multimodal projects for 21st century learning
 
Panelinstr
PanelinstrPanelinstr
Panelinstr
 
Elvis Collection Compilation
Elvis Collection CompilationElvis Collection Compilation
Elvis Collection Compilation
 
Corridade Toros[1]
Corridade Toros[1]Corridade Toros[1]
Corridade Toros[1]
 
Setmana D’Activitats ExtraordinàRies
Setmana D’Activitats ExtraordinàRiesSetmana D’Activitats ExtraordinàRies
Setmana D’Activitats ExtraordinàRies
 
Ep The Ftd Collection Vol2
Ep The Ftd Collection Vol2Ep The Ftd Collection Vol2
Ep The Ftd Collection Vol2
 
земляная смесь
земляная смесьземляная смесь
земляная смесь
 
Panelinstrph
PanelinstrphPanelinstrph
Panelinstrph
 
SheSpeaks Social Media Infographic
SheSpeaks Social Media InfographicSheSpeaks Social Media Infographic
SheSpeaks Social Media Infographic
 
How to Search Thai Digital Database
How to Search Thai Digital DatabaseHow to Search Thai Digital Database
How to Search Thai Digital Database
 
October 2010
October 2010October 2010
October 2010
 
How Firefox Works
How Firefox WorksHow Firefox Works
How Firefox Works
 

Similar a Creating Dynamic Charts With JFreeChart

Mongo db washington dc 2014
Mongo db washington dc 2014Mongo db washington dc 2014
Mongo db washington dc 2014ikanow
 
02 integrate highchart
02 integrate highchart02 integrate highchart
02 integrate highchartErhwen Kuo
 
SPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointSPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointMark Rackley
 
KNOWAGE CUSTOM CHART WIDGET: a technical guide
KNOWAGE CUSTOM CHART WIDGET: a technical guideKNOWAGE CUSTOM CHART WIDGET: a technical guide
KNOWAGE CUSTOM CHART WIDGET: a technical guideKNOWAGE
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...Anupam Ranku
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRoopa Nadkarni
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSébastien Levert
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphicsXamarin
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Matt Raible
 
Utilizing jQuery in SharePoint: Get More Done Faster
Utilizing jQuery in SharePoint: Get More Done FasterUtilizing jQuery in SharePoint: Get More Done Faster
Utilizing jQuery in SharePoint: Get More Done FasterMark Rackley
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 

Similar a Creating Dynamic Charts With JFreeChart (20)

Mongo db washington dc 2014
Mongo db washington dc 2014Mongo db washington dc 2014
Mongo db washington dc 2014
 
EPiServer Charts
EPiServer ChartsEPiServer Charts
EPiServer Charts
 
02 integrate highchart
02 integrate highchart02 integrate highchart
02 integrate highchart
 
SPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointSPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePoint
 
KNOWAGE CUSTOM CHART WIDGET: a technical guide
KNOWAGE CUSTOM CHART WIDGET: a technical guideKNOWAGE CUSTOM CHART WIDGET: a technical guide
KNOWAGE CUSTOM CHART WIDGET: a technical guide
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
Office 365 Saturday (Sydney) - SharePoint framework – build integrated user e...
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh K
 
Eclipse e4
Eclipse e4Eclipse e4
Eclipse e4
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Getting Started with CoreGraphics
Getting Started with CoreGraphicsGetting Started with CoreGraphics
Getting Started with CoreGraphics
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
 
Utilizing jQuery in SharePoint: Get More Done Faster
Utilizing jQuery in SharePoint: Get More Done FasterUtilizing jQuery in SharePoint: Get More Done Faster
Utilizing jQuery in SharePoint: Get More Done Faster
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 

Más de David Keener

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight ScenesDavid Keener
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space BattleDavid Keener
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive SettingDavid Keener
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for WritersDavid Keener
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century WriterDavid Keener
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten PassengersDavid Keener
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!David Keener
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineDavid Keener
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business ModelsDavid Keener
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook AppsDavid Keener
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsDavid Keener
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffoldDavid Keener
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsDavid Keener
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On RailsDavid Keener
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyDavid Keener
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteDavid Keener
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: RailsDavid Keener
 
Creating a World-Class RESTful Web Services API
Creating a World-Class RESTful Web Services APICreating a World-Class RESTful Web Services API
Creating a World-Class RESTful Web Services APIDavid Keener
 

Más de David Keener (20)

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight Scenes
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space Battle
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive Setting
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for Writers
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century Writer
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten Passengers
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business Models
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook Apps
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook Apps
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffold
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector Graphics
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case Study
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking Site
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: Rails
 
Creating a World-Class RESTful Web Services API
Creating a World-Class RESTful Web Services APICreating a World-Class RESTful Web Services API
Creating a World-Class RESTful Web Services API
 

Último

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 

Creating Dynamic Charts With JFreeChart

  • 1. Creating Dynamic Charts With JFreeChart By David Keener www.keenertech.com Copyright 2007 David Keener All rights reserved.
  • 2. Overview JFreeChart is an open source charting package implemented in Java. The focus of this presentation is on using JFreeChart to embed charts within web pages. After this presentation, you will be able to answer the following questions about this exciting technology: • What is JFreeChart? • Why would you want to use it? • What do you need to use it? • Where do you get it? • How can charts be embedded in Java-based web pages? • What if your web site isn’t Java-based?
  • 3. What Is JFreeChart? • Open source Java charting class library • Easy to use; with well-documented API • Supports dozens of chart types • Real-time chart generation • Extensive customization of charts • Can output charts in numerous formats • Mature technology – supported and enhanced since 2000
  • 5. Supported Chart Types • Pie Charts • Line Charts • Exploded Pie Charts • Bar Charts • Area Charts • Layered Bar Charts • Stacked Area Charts • Stacked Bar Charts • Candlestick Charts • Statistical Bar Charts • Time Series Charts • Waterfall Charts • Gantt Charts • Meter Charts • Dual Axis Charts • Ring Charts • Histograms • Scatter Plots • Time Series Charts • Etc.
  • 6. Prerequisites for Use • Java 2 Platform (JDK 1.3 or later) • JFreeChart 1.0.4 (as of February 9, 2007) • (Optional) Web Container, e.g. – Tomcat, WebLogic, etc.
  • 7. Where Do You Get It? JFreeChart Home Page - http://www.jfree.org/jfreechart/ JFreeChart Documentation • Free Installation Manual (PDF) • Generated API Documentation - http://www.jfree.org/jfreechart/api/gjdoc/index.html • Developer Manual (PDF) - Costs $48.75 for PDF download (well worth it!)
  • 8. Ways to Produce Charts JFreeChart is flexible enough to support a variety of ways to generate charts: • Servlet • Application • Applet For embedding charts within web sites, servlets are generally used.
  • 9. Servlet Review To create a servlet, perform these steps: • Create a class that extends the HttpServlet class • Provide an implementation for either the doGet() or doPost() methods • This method will produce the output that will be sent back to the requester
  • 10. The Basic Servlet import java.io.IOException; // Required Servlet Imports import java.io.OutputStream; import javax.servlet.*; import javax.servlet.http.*; import java.awt.Color; // Imports related to chart production import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class ChartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doTestPieChart(request, response); // Will produce chart } // End Method } // End Class
  • 11. Steps to Produce a Chart • Determine type of chart to be produced • Get the raw data for the chart • Store data in JFreeChart Dataset object • Create a Chart object – Of desired chart type and passing in the Dataset object • Customize Chart object as needed • Output generated chart in desired format
  • 12. Creating a Chart protected void doTestPieChart(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { OutputStream out = response.getOutputStream(); try { DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("Graphic Novels", 192); . . . JFreeChart chart = ChartFactory.createPieChart("Books by Type", dataset, true, false, false); chart.setBackgroundPaint(Color.white); // Customize chart response.setContentType("image/png"); ChartUtilities.writeChartAsPNG(out, chart, 400, 300); } catch (Exception e) { System.out.println(e.toString()); } finally { out.close(); } } // End Method
  • 13. Key Code Elements dataset.setValue("Graphic Novels", 192); . . . JFreeChart chart = ChartFactory.createPieChart("Books by Type", dataset, true, false, false); • Sets chart data items in a Dataset object (only one data line is shown) • Creates a chart with a title, a dataset and flags • Flags are: Yes for a legend, no for URLs and Tool Tips
  • 14. Key Code Elements 2 OutputStream out = response.getOutputStream(); . . . response.setContentType("image/png"); ChartUtilities.writeChartAsPNG(out, chart, 400, 300); • Gets output stream from Response • Sets mime type to “image/png” • Uses ChartUtilities class to write the chart out as a PNG • Writes the chart to the stream • Chart is never stored as a file
  • 15. Using the Servlet • References servlet with URL like this: http://www.site.com/servlet/ChartServlet • Servlet shows chart as an image • Not embedded within a web page… • How do you embed it within a web page?
  • 16. Embedding a Chart <html> <head> <title>Test Chart</title> </head> <body> <div align=center> <img src=“/servlet/ChartServlet” width=400 height=300 border=0> </div> </body> </html> • Uses a standard HTML IMG tag • The Tag references the chart servlet • Page loads; slight delay until chart shows
  • 17. Referencing the Servlet • Servlet can be referenced from anywhere • Nothing in embedding technique requires Java except the servlet itself • Non-Java sites can reference the servlet • Servlet can function as sort of a “poor man’s web service” • May need security for servlet to control where/how servlet is referenced
  • 18. Other Ways to Use JFreeChart • ChartUtilities class allows charts to be output in many formats, written to files, written to streams, etc. • Charts can easily be incorporated into servlets (as just shown), or applets or applications
  • 19. Summary The benefits of JFreeChart are: • Dynamic generation of very nice charts • Easy integration into web sites • Light-weight, with few dependencies • Flexible usage; easily customizable • Numerous chart types • Numerous ways to output charts