Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA FX + Javascript

I have never worked with JavaFX but right now I need to write a small application that will have embed browser and I need to pass some data to browser and get some data back from browser. As I have read I need to you JavaScript as a bridge for exchanging the data. I have tried a lot of examples like this:

http://knowles.co.za/javafx-and-javascript-calling-java-from-javascript/

http://www.java2s.com/Code/Java/JavaFX/WebEngineLoadListener.htm

but I can't make anything work.

Can someone give me working example?

like image 514
Irakli Avatar asked Feb 22 '26 23:02

Irakli


1 Answers

i think you are asking about interaction between javaFX an JavaScript

at first this operation is performed through Nashorn Engine

let's understand a simple example and write its complete code:

A problem: we want to get the sum of two number using javafx, JS, and html

suppose that we have HTML with

  1. two input fields to take values from the user
  2. button that calculate the sum of the numbers on the fields
  3. div in which we preview the sum of the numbers

when user click on the button it calls a JavaScript function that calls a java method which(ie: java method) receives the two numbers and returns the sum

so let's create a java class that has a method that calculates the sum of two numbers, it's so simple

public class Adder{

public double getSum(String a, String b)
{
    return Double.parseDouble(b) + Double.parseDouble(a);
}}

so we need to pass(inject) a java object to the javascript so we can use it to call methods, so how to inject a java object into the JS? simply use the following code

WebView browser = new WebView();
    browser.getEngine().getLoadWorker()
            .stateProperty()
            .addListener((obs, old, neww) ->
            {
                if (neww == Worker.State.SUCCEEDED)
                {
                    JSObject jsobj = (JSObject) browser.getEngine()
                            .executeScript("window");
                    jsobj.setMember("adder", new Adder());
                }
            });

we inject in the last line a java object(new Adder() ) and we give it a name(adder) to be used in the java script code, so the question now is how to use the adder in the JavaScript?

consider the following JavaScript function and call it add

function add()
        {
            var sum = adder.getSum("5", "7");
        }

as we see, it's very simply we just call the passed(injected) java object(Adder object) but the name adder and calls the method getSum("5","7")

now let's have a complete code

1- create a new JavaFX project in your IDE and named the main class NashornTest and here's the code

import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class NashornTest extends Application{

@Override

public void start(Stage stage)
{

    //create an embeded web browser
    WebView browser = new WebView();

    browser.getEngine().getLoadWorker()
            .stateProperty()
            .addListener((obs, old, neww) ->
            {
                if (neww == Worker.State.SUCCEEDED)
                {
                    // Let JavaScript make calls to adder object,
                    //so we need to inject an [Adder] object into the JS code
                    JSObject bridge = (JSObject) browser.getEngine()
                            .executeScript("window");
                    bridge.setMember("adder", new Adder());
                }
            });
    //load the html page
    browser.getEngine().load(NashornTest.class.getResource("index.xhtml").toString());
    VBox box = new VBox(browser);

    Scene scene = new Scene(box);
    stage.setScene(scene);
    stage.show();
}

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

2-create a java class and called it Adder, and here's the code

public class Adder{

public double getSum(String a, String b)
{
    return Double.parseDouble(b) + Double.parseDouble(a);
}}

3-create an XHTML file and call it index.xhtml and here's the scripts, it must be in the same java package of the NashornTest.java

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <script>
            function add()
            {
                var num1 = document.getElementById("num1Field").value;
                var num2 = document.getElementById("num2Field").value;
                //make calls for injected java object
                var sum = adder.getSum(num1, num2);
                document.getElementById("outputDiv").innerHTML = "sum = " + sum;
            }

        </script>
    </head>
    <body>
        <input id="num1Field"/>
        <input id="num2Field"/>
        <button onclick="add()">sum</button>
        <div id="outputDiv"></div>
    </body>
</html>

at the end this is a simple start for interaction between Java and JavaScript, and i hope this post is helpful and useful

like image 155
Anas Avatar answered Feb 24 '26 13:02

Anas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!