DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Embed a JavaFX Chart in a Visual Library Scene

How to Embed a JavaFX Chart in a Visual Library Scene

Sean Phillips user avatar by
Sean Phillips
·
Apr. 21, 13 · Interview
Like (0)
Save
Tweet
Share
15.98K Views

Join the DZone community and get the full member experience.

Join For Free

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() {
            super();
            // create JavaFX scene
            Platform.setImplicitExit(false);
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    createScene();
                }
            });  
        }
        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();
            xAxis.setLabel("X-Axis");
            yAxis = new NumberAxis();
            yAxis.setLabel("Y-Axis");
    
            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);
            root.getChildren().add(chart);     
    
            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); 
            xAxis.setLabel("log(1:1000)");
            yAxis.setLabel("random(1:1000)");        
            
            
            this.setScene(new Scene(root));
            this.validate();
        }     
        public void updateXY(final String seriesTitle, final Double [] xArray, final Double [] yArray) {
            Platform.setImplicitExit(false);
            Platform.runLater(new Runnable() {
                @Override
                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() {
            initComponents();
            setName(Bundle.CTL_JavaFXWidgetTestTopComponent());
            setToolTipText(Bundle.HINT_JavaFXWidgetTestTopComponent());
            setLayout(new BorderLayout());
            add(scrollPane,BorderLayout.CENTER);
            //Setup visual library scene
            scene = new VMDGraphScene();
            scrollPane.setViewportView(scene.createView());  
            //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
            widget.addChild(componentWidget); 
    
            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.

JavaFX Library Chart NetBeans application API app Data (computing) Concept (generic programming)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Set Up and Run Cypress Test Cases in CI/CD TeamCity
  • 19 Most Common OpenSSL Commands for 2023
  • How To Select Multiple Checkboxes in Selenium WebDriver Using Java
  • A Beginner's Guide to Infrastructure as Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: