Wednesday, December 5, 2012

Using JFreeChart in your RCP

JFreeChart is a charting library available under LGPL. Designed for AWT/Swing it takes some (minor) effort to make it work with SWT. There is a tutorial available from Lars Vogel which shows how to use this with swing, so I will focus on how to integrate this into your own plug-ins.

Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online.External libraries needed for this tutorial are not provided on my github site!

Step 1: Create the JFreeChart plug-in

We will put all required libraries into a separate plug-in. First we need to download JFreeChart. Unzip the archive and switch back to Eclipse.

Create a new Plug-in from Existing JAR Archives. On the Jar selection page add jfreechart-1.0.19.jar, jfreechart-1.0.19-swt.jar and jcommon-1.0.23.jar from jfreechart/lib folder. You can do this by using the Add External... button.

On the next page set the Project name to org.jfree.chart and uncheck Unzip the JAR archives into the project. Then finish the wizard.

The manifest file is automatically opened. Switch to the Dependencies tab and add a dependency to org.eclipse.swt.

Step 2: Create a sample chart

For the view I created a separate plug-in. Add org.jfree.chart as a dependency and define a new view. The source code is pretty straight forward and mostly taken from Lars' tutorial.
package com.codeandme.jfreechart;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.util.Rotation;

public class DemoView extends ViewPart {

 public void createPartControl(Composite parent) {
  final PieDataset dataset = createDataset();
  final JFreeChart chart = createChart(dataset, "Operating Systems");

  new ChartComposite(parent, SWT.NONE, chart, true);

 private PieDataset createDataset() {
  final DefaultPieDataset result = new DefaultPieDataset();
  result.setValue("Linux", 29);
  result.setValue("Mac", 20);
  result.setValue("Windows", 51);
  return result;

 private org.jfree.chart.JFreeChart createChart(final PieDataset dataset, final String title) {
  final JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
  final PiePlot3D plot = (PiePlot3D) chart.getPlot();
  return chart;

 public void setFocus() {

To use JFreeChart under SWT you create a chart the same way as for Swing and display it using a ChartComposite (see line 21).

Your view should look like this:

If you use JFreeChart in your own products remember that it is licensed under LGPL. Consider buying the developers guide to support this great library.