简体   繁体   中英

How do I pass a variable between JavaFX to javaScript?

How do I pass variable from Java(JavaFx) to JavaScript? I think I have to use executeScript , but I am not sure how to really use it. Basically I want to a program that sends elements in arraylist from java into the array in javaScript. The code below is the Java code that I wrote. Hope someone could help me out. Thank you in advance.

import java.util.ArrayList;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class UserInterface extends Application{
    Button btn_js;

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

    @Override
    public void start(Stage stage) throws Exception {
        WebView myWebView = new WebView();
        WebEngine engine = myWebView.getEngine();
        ArrayList<String> arr = new ArrayList<String>();
        btn_js = new Button("fire js");
        btn_js.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                //engine.executeScript("something goes here to transfer data to js");
        }
        });
        VBox root = new VBox();
        root.getChildren().addAll(myWebView, btn_js);
        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();
    }
}

As you think you can use executeScript .

You can write for example a javascript function that does something on the passed array. To pass the array from Java to Javascript, you have to transform it to Javascript format (manually or by using JSon for example).

Here is an example:

Here the javascript function is loaded using loadContent which will loop through the passed array and will create and alert for each element. On Java side each alert is printed using setOnAlert .

On a JavaFX button press, the function is executed by:

myWebView.getEngine().executeScript("printArray(" + transformToJavascriptArray(arr) + ")"));

where transformToJavascriptArray will transform the Java List to a Javascript array (I am doing this manually).

public class UserInterface extends Application {
    Button btn_js;

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

    @Override
    public void start(Stage stage) throws Exception {
        WebView myWebView = new WebView();

        myWebView.getEngine().loadContent("<html>\n" 
                        + " <script>function printArray(arr) {" 
                        + "for (i = 0; i < arr.length; i++) {"
                        + " window.alert(arr[i]);" 
                        + "}"
                        + "} </script> " 
                        + "    </body>\n" 
                        + "</html>");

        List<String> arr = new ArrayList<String>();
        arr.add("Dog");
        arr.add("Cat");

        btn_js = new Button("fire js");
        btn_js.setOnAction(e -> myWebView.getEngine().executeScript("printArray(" + transformToJavascriptArray(arr) + ")"));

        myWebView.getEngine().setOnAlert(event -> System.out.println("JS alert: " + event.getData()));

        VBox root = new VBox();
        root.getChildren().addAll(myWebView, btn_js);
        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.show();
    }

    private String transformToJavascriptArray(List<String> arr) {
        StringBuffer sb = new StringBuffer();
        sb.append("[");

        for (String str : arr)
            sb.append("\"").append(str).append("\"").append(", ");

        if (sb.length() > 1)
            sb.replace(sb.length() - 2, sb.length(), "");

        sb.append("]");

        return sb.toString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM