Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Nashorn Application with NetBeans 8

DZone's Guide to

Nashorn Application with NetBeans 8

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Java SE 8 has been out for a couple of days now. I discovered several strong new features, but the most interesting one for me is Nashorn (JSR223). Thanks to this specification, Java meets, once again, script languages and, especially, JavaScript, which is the major internet language of the moment.

I would like to celebrate also the release of the latest version of NetBeans IDE by presenting a small application mixing Nashorn APIs and Swing APIs. Of course, it will be built using NetBeans IDE 8!

The project comprises the following:

  • a Javscript, FibScript, file containing a non recursive Fibonacci number function (Fibonacci
  • a form, FormUser, based on Swing APIs, that helps the user to input a range of integers and calculates the Fibonacci number of each integer
  • a class, FibonacciCalcul, that uses some Nashorn classes
function Fibonacci(n) {
    var a ; 
    if(n <= 0)return 0 ; 
    if(n == 1) return 1;
    var b = 0;
    var c = 1;
    for (var i=2;i <= n ; i++) {
        a = b+c ; 
        b=c; 
        c = a ;         
    }; 
    return c;     
}
(FibScript.js)

package calculus;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class FibonacciCalcul {

    public FibonacciCalcul() {
        
    }
    
    public int myNashornFileExecution(int n) throws ScriptException, NoSuchMethodException {
        
        final ScriptEngineManager factory = new ScriptEngineManager(); 
        final ScriptEngine engine  = factory.getEngineByName("nashorn");
                
        //Create the builder here
        final InputStream inputStream  = Thread.currentThread().getContextClassLoader().getResourceAsStream("calculus/FibScript.js"); 
        final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        engine.eval(inputStreamReader);
        
        //Invoke a function from a Javascript file
        final Invocable invocable = (Invocable)engine ; 
        final int fib = (int)invocable.invokeFunction("Fibonacci", n);
        return fib ;        
    }
        
}
(FibonacciCalcul.java)

  private void buttonSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSubmitActionPerformed
        // TODO add your handling code here:
        
        FibonacciCalcul fibo  = new FibonacciCalcul(); 
        
        for(int i= Integer.parseInt(txtLowerBound.getText()) ; i <= Integer.parseInt(txtUpperBound.getText()); i++) {
            try {
                txtResult.append("Fibonacci of " + i + " is " + fibo.myNashornFileExecution(i) + "\n");
                txtResult.setCaretPosition(txtResult.getDocument().getLength());
            } catch (ScriptException ex) {
                Logger.getLogger(FormUser.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(FormUser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }/
(Method used by the submit button.)

Here below a screenshot of the project:


The result after successful compilation:

So, enjoy NetBeans 8 and Java 8!

There are lot of resources on the internet that could help you to build a more professional and complete application. Here is a list of pages that inspired me:

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}