JFreeChart in Eclipse RCP & SWT

To use JFreeChart in a Eclipse RCP project or simply embed in an SWT composite, you have two applicable choices: org.jfree.experimental.chart.swt.ChartComposite from JFreeChart SWT experimental project, which I can not say works seamless.

SWT_AWT bridge, hmm, not perfect but plays its role better.

  • Create a container composite with SWT.EMBEDED style (required for SWT_AWT).
<span class="n">Composite</span> <span class="n">container</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Composite</span><span class="o">(</span><span class="n">parent</span><span class="o">,</span> <span class="n">SWT</span><span class="o">.</span><span class="na">EMBEDDED</span><span class="o">)</span>
  • Create new AWT Frame using container.
<span class="n">java</span><span class="o">.</span><span class="na">awt</span><span class="o">.</span><span class="na">Frame</span> <span class="n">chartFrame</span> <span class="o">=</span> <span class="n">SWT_AWT</span><span class="o">.</span><span class="na">new_Frame</span><span class="o">(</span><span class="n">container</span><span class="o">)</span>
  • Create a JFreeChart ChartPanel and append on chartFrame. (This should be done in AWT Event Thread)
<span class="n">SwingUtilities</span><span class="o">.</span><span class="na">invokeLater</span><span class="o">(</span><span class="k">new</span> <span class="nf">Runnable</span><span class="o">()</span> <span class="o">{</span>
     <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
          <span class="n">ChartPanel</span> <span class="n">chartPanel</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">ChartPanel</span><span class="o">(</span><span class="n">chart</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span>
          <span class="n">chartFrame</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">chartPanel</span><span class="o">);</span>
     <span class="o">}</span>
<span class="o">})</span>

That's it!

Migrated from old blog: jfreechart-in-eclipse-rcp-swt