Embedding Java 3D objects in a JavaFX application

In a previous post I showed how to embed and display Java 3D objects in a Swing application, using the Canvas3D class for that purpose.

Java 3D and the JavaFX 3D classes are both live projects (*), and similar, but not equal, libraries with a similar set of functions. All that means that there are valid reasons to choose one over the other.

The case with the Swing libraries is different since there is an explicit intention by Oracle of gradually phasing out the Swing library in favor of JavaFX's components. Also, in my very limited experience with both, Swing doesn't seem to hold any particular advantage. Not even in tooling, thanks to Scene Builder.

In summary, there are valid reasons to choose both JavaFX and Java 3D classes to build a Java desktop application that displays 3D graphics.

In this post I will present a minimal example of integrating both in an application. 

Note that this time we can only use Swing lightweight components. Otherwise they may fail to be rendered by JavaFX. That means we need to replace the class Canvas3D that we used in the Java 3D - Swing integration example with its lightweight pure-Java counterpart JCanvas3D.

I had to rely on a hack in the JFrame class. There is an issue with the dimensions of a component at the time of adding the SwingNode that I was not able to resolve and results in an exception being thrown.

However, while debugging and stepping over the code, I noticed that sometimes the frame would be rendered correctly. Then I simply decided to retry adding the SwingNode if it failed the first time and noticed it would correctly render the panel in a very reliable way. I suspect there is a simple and cleaner solution, but at least the code demonstrates that the integration is completely possible.

We are not out of trouble yet. When I tried to integrate the rest of functionality that I had already developed in a Swing application, I noticed some features wouldn't work. It seems Java 3D, Swing and JavaFX simply don't play well together.

With that in mind I still think someone will benefit by going this route and won't have so much trouble with their applications as I had.

(*) Although new developments of Java 3D classes continue as a third party project and will not be integrated in the JDK in any foreseeable future.

Comments