Over a million developers have joined DZone.

How to Embed a JavaFX Chart in a Visual Library Scene

DZone 's Guide to

How to Embed a JavaFX Chart in a Visual Library Scene

· Java Zone ·
Free Resource

JavaFX really shines as an enhancer technology for existing Java/Swing applications and code bases.  A Java developer who understands Swing but is just starting to explore JavaFX can easily upgrade his or her software on a component by component basis.  For example, let's say we have a NetBeans Platform application with a Visual Library scene which are both Swing platforms and we want to add a JavaFX chart to the scene.  Something like this:

This is easier than it sounds and is made possible using a standard JavaFX/Swing Interop pattern. So this article will show how to build a Swing Interop component that could be used to accomplish this. Then it will show how to take this new interop component and actually embed it within a Visual Library scene.

First you will need to do a little prep work to setup an application for this tutorial.  If you don't already have a NetBeans Platform app with a Visual Library scene do the following:

  1. Create the Application. Create a new NetBeans Platform application and add the following modules in the Libraries tab of the Project Properties:
    • Settings API
    • UI Utilities API
    • Utilities API
    • Visual Library API
    • Window System API
    • Lookup API
  2. Include the JavaFX Runtime. Create a NetBeans library wrapper module to include "jfxrt.jar" and set a dependency on it in the module described above.

  3. Add a new class to the module's package that extends type JFXPanel. We will be writing our JavaFX specific code in this class.  The JFXPanel is a swing embeddable component that is largely treated as a traditional JPanel.  JFXPanel is a swing interop-able class that is "JavaFX aware".  We use the JFXPanel Platform.runLater pattern so that the JavaFX components can be rendered on the JavaFX runtime thread.
    Below is this constructor pattern:

    public class LineChartJFXPanel extends JFXPanel {
        private LineChart chart;
        private NumberAxis xAxis;
        private NumberAxis yAxis;    
        private ObservableList<XYChart.Series<Double,Double>> lineChartData;
        public LineChartJFXPanel() {
            // create JavaFX scene
            Platform.runLater(new Runnable() {
                public void run() {
        private void createScene() {
            Group root = new Group();
            //xAxis = new NumberAxis("Values for X-Axis", 0, 3, 1);
            //yAxis = new NumberAxis("Values for Y-Axis", 0, 3, 1);
            xAxis = new NumberAxis();
            yAxis = new NumberAxis();
            Integer theSize = 200;
            lineChartData = FXCollections.observableArrayList(
                new LineChart.Series<>("Series 1", FXCollections.observableArrayList(
                    new XYChart.Data<>(0.0, 0.0)
            chart = new LineChart(xAxis, yAxis, lineChartData);
            Double [] xDoubleArray = new Double[theSize];
            Double [] yDoubleArray = new Double[theSize];
            for(int i = 0;i < theSize;i++) {
                Double x = new Double(java.lang.Math.log(i));
                if(x.isInfinite() || x.isNaN())
                    x = 0.0;
                xDoubleArray[i] =  x;
                yDoubleArray[i] =  new Double(java.lang.Math.random()*i);
            updateXY("log(1:1000) / random(1:1000)",xDoubleArray, yDoubleArray); 
            this.setScene(new Scene(root));
        public void updateXY(final String seriesTitle, final Double [] xArray, final Double [] yArray) {
            Platform.runLater(new Runnable() {
                public void run() {
                    //convert double arrays to a typed list
                    List <XYChart.Data> xyChartDataList = new ArrayList<>();
                    for(int i=0;i<xArray.length;i++) {
                        xyChartDataList.add(new XYChart.Data<>(xArray[i],yArray[i]));
                    //Wrap typed list in ObservableList wrapper collection
                    ObservableList<XYChart.Data> observableList = FXCollections.observableList(xyChartDataList);    
                    //add new ObservableList collection to chart
                    lineChartData.setAll( new LineChart.Series(seriesTitle,observableList));
    Notice that to update the chart data a convenience method was created "updateXY()"?  This is a simple example of providing a way to update the chart.  Notice how it too follows the Platform.runLater() pattern. This is good enough for the tutorial but to truly be useful you would need to improve your interface to include methods that create and remove data series.  Plus you would definitely want to then use these methods as part of a registered Service or Lookup mechanism inside the NetBeans Platform.  These concepts are a bit beyond the scope of this tutorial and warrant their own dedicated discussion.  For now you have a new JavaFX component class that can be placed into any existing Swing component tree.

  4. Create TopComponent with Visual Library Scene: Use the New Window wizard to create a TopComponent.  This TopComponent will have the Scene and a Node widget.  Inside the Node widget we will add an instance of our new LineChartJFXPanel class.  Neither the TopComponent nor the Visual Library scene are going to know or care about JavaFX.

    Below is this setup code within the TopComponent constructor:

    public final class JavaFXWidgetTestTopComponent extends TopComponent {
        private VMDGraphScene scene;
        private JScrollPane scrollPane = new JScrollPane(); 
        public LineChartJFXPanel lineChartPanel;
        public JavaFXWidgetTestTopComponent() {
            setLayout(new BorderLayout());
            //Setup visual library scene
            scene = new VMDGraphScene();
            //Initialize and add JavaFX chart widget
            //Line chart
            lineChartPanel = new LineChartJFXPanel();
            //create our new node in the scene 
            VMDNodeWidget widget = (VMDNodeWidget) addNode ("JavaFX Chart");
            //Add our JavaFX panel to a ComponentWidget which is adept at embedding Swing components
            ComponentWidget componentWidget = new ComponentWidget(scene, lineChartPanel);
            //The JavaFX chart component is now a child of this node and can be found as such
            scene.getSceneAnimator().animatePreferredLocation(widget, getMousePosition(true));
            scene.validate(); //Make sure you validate the scene so that everything renders nicely

    The rest of the auto-generated TopComponent code should be fine.  I chose to use the VMD classes of the Visual Library (VMDGraphScene and VMDNodeWidget) because they provide out of the box collapsible Nodes and I wanted to see how the JavaFX rendering behaved.  Pretty good actually though occasionally the VMDNodeWidget needs a user issued collapse/expand combo to render the first time.  This may be due to the quantity of numbers be calculated combined with the fact that the LineChart class's constructor is rendering on a separate thread from Swing.

At this point you can clearly reuse this approach and make an assortment of JavaFX components and drop them into not only Visual Library scenes but any TopComponent of the Netbeans Platform.  Below is a screenshot of this model extended to multiple charts integrated with a palette tool:

Embedding multiple JavaFX charts in a Visual Library scene

This screenshot was also seen in an article onGeertjan's Blog.

This is an example of how JavaFX can be used to enhance the already great Swing based NetBeans Platform.  I think for the future those that are interested in demonstrating or using JavaFX inside their Swing and NetBeans Platform apps need to first take a deep look at JavaFX and what compelling things it does better than Swing.  There are numerous use cases such as the above throughout the NetBeans Platform where this could be leveraged.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}