Pular para o conteúdo principal

Writing JavaFX apps using Javascript with the Java 8 Nashorn engine

Java 8 was just a great release! We already talked about Lambdas and created JavaFX 8 apps on this blog. Bruno Borges created a fx2048, a JavaFX version of the famous 2048 game, which shows Lambdas and the Stream library usage.

Today I'll rewrite the Sentiments App view in Javascript using the new JS engine named Nashorn, one of the exciting Java 8 new features.

Loading the Script


We load a file with the view contents, but before doing this, we add the main Stage so it can be referenced from the javascript file. That's enough for the Java part!

package org.jugvale.sentiments.view;

import javafx.application.Application;
import javafx.stage.Stage;
import javax.script.*;
import java.io.FileReader;

public class AppJS extends Application{

        private final String SCRIPT = getClass().getResource("/sentimentsView.js").getPath();

        public static void main(String args[]){
                launch(args);
        }   

        @Override
        public void start(Stage stage){
                try{
                        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
                        engine.put("stage", stage);
                        engine.eval(new FileReader(SCRIPT));
                }catch(Exception e){ 
                        e.printStackTrace();
                }   
        }   
 }



Notice in my case I'm calling the script from my Java code, but it's possible to use jjs to invoke scripts and build JavaFX apps.

Writing Javascript

After this, we can already start writing Javascritp code and leave Java behind for a moment. The core of the application (the service and model classes)  is written in Java and we can refer to it in our JS.

The good parts

The best thing about JS I can highlight is that we don't need to use get/set methods anymore! Nashorn threat Java beans properties (those accessed by get and set methods) as an object property and behind the scenes it will invoke the get/set methods!
We also take full advantage of the scripting language: don't need to use semiclon, easier to declare variables, more clar
I liked the fact that I don't need to recompile the class to update the view. If I modify the script and re-run the java part, the view will be updated!

The bad parts

I didn't like how to handle the imports. It seems that I have to either declare the type or write the FQN of a class to instantiate it.
I also prefer Java and FXML over writing the view in pure javascript. Remember you can script on FXML as well!

Code and running

Here's the final script for the Sentiments App view:

// Imports
var Scene = Java.type('javafx.scene.Scene')
var VBox = Java.type('javafx.scene.layout.VBox')
var Label = Java.type('javafx.scene.control.Label')
var TextField = Java.type('javafx.scene.control.TextField')
var PieChart = Java.type('javafx.scene.chart.PieChart')
var TableView  = Java.type('javafx.scene.control.TableView')
var TableColumn  = Java.type('javafx.scene.control.TableColumn')
var PropertyValueFactory  = Java.type('javafx.scene.control.cell.PropertyValueFactory')
var SearchService  = Java.type('org.jugvale.sentiments.service.SearchService')
var TextSentimentService  = Java.type('org.jugvale.sentiments.service.TextSentimentService')
var TableView  = Java.type('javafx.scene.control.TableView')
var FXCollections = Java.type('javafx.collections.FXCollections')

// variable declaration
var root = new VBox(10)
var txtQuery = new TextField()
var table = new TableView()
var chart = new PieChart()
var textSentimentService = new TextSentimentService()
var searchService = new SearchService()

// main block
root.children.addAll(txtQuery, chart, table)
stage.scene = new Scene(root)
stage.title = "Sentiments"
stage.width = 400
stage.height = 550
stage.show()
initializeApp()
// functions 
function initializeApp(){
 txtQuery.promptText = "Enter your query for text and press enter"
 chart.title = "Sentiments for \"" + txtQuery.getText() +"\""
 txtQuery.onAction = queryAction
 addTableColumns()
 queryAction(null)
}
function queryAction(e){
 var textSentiments = getTextSentiments(txtQuery.getText());
 fillTable(textSentiments);
 fillChart(textSentiments);
}
function fillTable(textSentiments){
 table.items = FXCollections.observableList(textSentiments)
}
function fillChart(textSentiments){
 var polarity0Count = textSentiments.stream().filter(function (s) s.getPolarity() == 0).count();
 var polarity2Count = textSentiments.stream().filter(function(s)  s.getPolarity() == 2).count();
 var polarity4Count = textSentiments.stream().filter(function(s)  s.getPolarity() == 4).count();
 chart.data = 
  FXCollections.observableArrayList(
   new PieChart.Data(":(", polarity0Count),
   new PieChart.Data(":|", polarity2Count),
   new PieChart.Data(":)", polarity4Count)
 )
}
function getTextSentiments(q){
 return textSentimentService.getSentiments(query(q)).textSentiments
}
function addTableColumns(){
 var textCol = new TableColumn("Text")
 var polarityCol = new TableColumn("Polarity")
 textCol.cellValueFactory = new PropertyValueFactory("text")
 textCol.minWidth = 200
 polarityCol.cellValueFactory = new PropertyValueFactory("polarity")
 polarityCol.minWidth = 80
 polarityCol.resizable = false
 table.columns.setAll(textCol, polarityCol)
}
function query(q){
 if(!q || q.trim().isEmpty()){
  return java.util.Arrays.asList("obama is awesome", "obama sucks", "obama eats potato");
 }else{
  return  searchService.search(q, SearchService.Provider.TWITTER);
 }
}


The full code is on github and you can build it by simply typing the following maven instruction on command line (remember to have maven and JAVA_HOME pointing to your Java 8 installation root directory):

$ mvn package exec:java -Dexec.mainClass="org.jugvale.sentiments.view.AppJS" -DskipTests

Conclusion

Using Javascript from Java is easy and with the new JS engine we have increased the performance due the Invoke Dynamic feature.
Using JS can be a good advantage for a team who has JS programmers and needs to build a desktop app, so we can use their full potential on Javascript and take all advantages and libraries from Java.

Comentários

Postagens mais visitadas deste blog

Creating custom Work Item Handler in BPM Suite/jBPM 6

Hi all! In this post I am going to share my experience creating a work item handler for BPM Suite 6.0.3 (which is very similar to jbpm as explained in a previous post ). The Hello World Work Item Handler Let's create a really simple WorkItemHandler just to print "Hello World" in the console. Of course you can implement more feature and make it receive parameters, access database, web services, etc. But in this post we will keep it simple. Really simple. First thing to do is to create a maven project for my WorkItemHandler. Here's the pom.xml of my Maven project: Notice that we are importing jbpm dependency so we can find the java interface that is used to create work item handlers. Now we can start coding. Let's create a class name HelloWorkItemHandler in package org.jugvale.jbpm, here is the simple code: Now we can build our project and go to BPM Suite to configure it so we can use this workitem. Registering the WorkItemHandler UPDATE...

Simplest JavaFX ComboBox autocomplete

Based on this Brazilian community post , I've created a sample Combobox auto complete. What it basically does is: When user type with the combobox selected, it will work on a temporary string to store the typed text; Each key typed leads to the combobox to be showed and updated If backspace is type, we update the filter Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:   The class code and a sample application is below. I also added the source to my personal github , sent me PR to improve it and there are a lot of things to improve, like space and accents support.

Dancing lights with Arduino - The idea

I have been having fun with Arduino these days! In this article I am going to show how did I use an electret mic with Arduino to create a Dancing Lights circuit. Dancing Lights   I used to be an eletronician before starting the IT college. I had my own electronics maintenance office to fix television, radios, etc. In my free time I used to create electronic projects to sell and I made a few "reais" selling a version of Dancing lights, but it was too limited: it simply animated lamps using a relay in the output of a 4017 CMOS IC. The circuit was a decimal counter  controlled by a 555. 4017 decimal counter. Source in the image When I met Arduino a few years ago, I was skeptical because I said: I can do this with IC, why should I use a microcontroller. I thought that Arduino was for kids. But now my pride is gone and I am having a lot of fun with Arduino :-) The implementation of Dancing Lights with Arduino uses an electret mic to capture the sound and light leds...