X

Geertjan's Blog

  • March 30, 2015

Extending NetBeans with Nashorn

Geertjan Wielenga
Product Manager

Let's take our JavaScript/JavaFX code (for running Yeoman and displaying results in JavaFX) and integrate it into a NetBeans module. At the end of this blog entry you'll have a NetBeans module that looks as follows:

The 'yeoman.js' file is similar to the one blogged about here. Slightly tweaked, it's at the end of this blog entry.

It's registered in the layer file above like this:

<folder name="nashorn">
<file name="yeoman" url="nbres:/org/netbeans/modules/yeoman/yeoman.js"/>
</folder>

And here's the code in an Action (e.g., invoked from a menu item) that finds the JavaScript file and evaluates it via Nashorn:

Import statements:

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

Here's the JavaScript, i.e., runs Yeoman and displays results in JavaFX:

/* global $OUT, generator, FXCollections, javafx, $STAGE */
var WebView = javafx.scene.web.WebView;
var StackPane = javafx.scene.layout.StackPane;
var Scene = javafx.scene.Scene;
var FXCollections = javafx.collections.FXCollections;
var Label = javafx.scene.control.Label;
var ComboBox = javafx.scene.control.ComboBox;
var VBox = javafx.scene.layout.VBox;
var HBox = javafx.scene.layout.HBox;
var stage = javafx.stage.Stage;
$EXEC("C:/Users/gwieleng/AppData/Roaming/npm/yo.cmd");
var output = $OUT;
var cleanedOutput = [];
output = output.substring(81, output.length - 553).split("\n");
for each(generator in output) {
if (generator.length > 0) {
cleanedOutput.push(generator);
}
}
options = FXCollections.observableArrayList(cleanedOutput);
selectedGenerator = new Label();
selectedGenerator.setFont(javafx.scene.text.Font.font(24));
comboBox = new ComboBox(options);
comboBox.setValue(options[0]);
comboBox.valueProperty().addListener(new javafx.beans.value.ChangeListener({
changed: function (observableValue, oldSelection, newSelection) {
selectedGenerator.setText(newSelection);
}
}));
var root = new VBox(10);
var box1 = new HBox(10);
var box2 = new HBox(10);
box1.children.addAll(new Label("Choose a generator: "), comboBox);
box2.children.addAll(selectedGenerator);
root.children.addAll(box1, box2);
var stage = new javafx.stage.Stage();
stage.scene = new Scene(root, 400, 300);
stage.title = "Yeoman Generator";
stage.show(); 

Further reading:

http://stackoverflow.com/questions/26873201/enable-scripting-mode-for-nashorn-in-java

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.