Migrating Java2D Code to JavaFX


Here at Object Refinery we have built two products, JFreeChart and Orson Charts, that rely heavily on Java2D, specifically the Graphics2D API. Java2D is a great technology that isn't going away but, as everyone knows, the future of Java desktop development is JavaFX. For our clients already making the move to JavaFX, we want to make it as easy as possible for them to continue using JFreeChart and Orson Charts, and avoid having to significantly rework their code that produces charts and reports...but how?

There exists a JavaFX Canvas component which can be used to "draw" vector output in the same way as you do with Java2D but, unfortunately, Oracle chose not to provide a Graphics2D API for this component, instead opting for an API that is roughly equivalent to that used by the HTML5 Canvas. We decided to fix that.


Read on to find out how we did it, and in the process future-proofed JFreeChart and Orson Charts (and maybe your code too).


We've previously implemented the Graphics2D API targetting SVG output (JFreeSVG) and PDF (OrsonPDF) with great results, so we decided that a new Graphics2D implementation targetting the JavaFX Canvas would very likely solve our problem, minimising the disruption to our code, our clients' code, and also the cost of supporting both Java2D/Swing and JavaFX going forward.

FXGraphics2D is our shiny new bridge class that maps Java2D drawing calls directly to the equivalent JavaFX Canvas API methods. The code is small, fast, free (under a very liberal BSD-style license), and available now on GitHub. So far in our testing, the code performs well and generates high-quality output. Now with our first public release, we are looking forward to feedback from a diverse range of users.


There are a couple of demos included with the project on GitHub (one for JFreeChart and one for Orson Charts). The screenshot from the JFreeChart demo (with source code here) appears above.

The Orson Charts demo is larger and more interactive than what we have for JFreeChart so far. Here is a screenshot (we encourage you to download the code and try it out live, particularly to see the tooltip and mouse event support):



Faced with the problem of supporting JFreeChart and Orson Charts users wishing to migrate to JavaFX, we've created FXGraphics2D, a small, fast, elegant and free solution that bridges the divide between Java2D and JavaFX.

If you'd like to give feedback on this post, please comment via the FXGraphics2D forum.