user2084435
user2084435

Reputation: 5

Using Nashorn/JavaScript to Create a Java GUI application

I am attempting to create an application(game) that would use java to operate the physics,logic, etc. but would use existing javascript libraries for doing things like scripting, graphics, and the ui, but when loading a chart.js(and other libraries) through nashorn nashorn.eval("load('chart.js')"); I get the following (or similar for other libraries) Exception in thread "main" javax.script.ScriptException: ReferenceError: "window" is not defined in chart.js at line number 668.

Is it possible to use these libraries as-is, or would any modification by necessary, and how could I display scripts in a java application(or is it even possible, with or without nashorn)?

Thanks.

Upvotes: 0

Views: 1335

Answers (2)

A. Sundararajan
A. Sundararajan

Reputation: 4405

As mentioned you can use JavaFX WebView to load "browser" HTML+script into Nashorn JavaFX GUI. You can load generated HTML as well as from a URL.

Simple examples:

http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/showsysprops.js http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/showenv.js

You can also access "browser" JS/DOM objects from Nashorn engine and manipulate with nashorn script (if needed):

http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/browser_dom.js

Given that you're going to use Java libraries, you may also want to consider JavaFX GUI without WebView as well (or even mix-n-match as needed). Few simple examples here:

http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/jsonviewer.js http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/time_color.fx http://hg.openjdk.java.net/jdk9/dev/nashorn/file/f884dff432a7/samples/fxml_example.js

Somewhat complex example of loading a third-party HTML+script into a JavaFX GUI and extending it from nashorn script:

https://gist.github.com/sundararajana/7b19ec08a8878426af5e

Upvotes: 2

David P. Caldwell
David P. Caldwell

Reputation: 3821

You may, however, be able to persuade this to run in the JavaFX WebView container. I have not tried using advanced JavaScript libraries in the container but my experience is:

  • The container works fairly well,
  • It is difficult to debug applications running in it, as there are very few mechanisms for doing so,
  • The mechanisms for communicating back to the Java application are fairly good,
  • You can provide custom handling for application-specific protocols for URLs, but it is not clear to me how these would affect the WebView's security model (unless you updated the http: or https: stream handlers, which appears to be possible using the URL.setURLStreamHandlerFactory method).

Upvotes: 1

Related Questions