JavaFx到Javascript。传递参数的正确方法是什么。

时间:2016-08-25 21:50:30

标签: javascript java javafx

我正在尝试学习如何使用JavaFX,而且我不知道将值传递给JS并从JS返回值的正确方法是什么。

此代码工作正常,但我不知道它是否是正确的编码。如果您对如何正确操作有任何建议,请告诉我。

谢谢。

JavaFX Class

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;


public class NewFXMain extends Application {
    private String msg;
    private String name = "Vader";
    @Override
    public void start(Stage primaryStage) {

        WebView browser = new WebView();
        WebEngine webEngine = browser.getEngine();
        webEngine.load(getClass().getResource("HelloWorld.html").toString());

        Button btn = new Button();
        btn.setText("DO you want to know my secret Identity?!!!");
        btn.setOnAction(new EventHandler<ActionEvent>() {        
            @Override
            public void handle(ActionEvent event) {

               //Pass this to javascript
               webEngine.executeScript("myName("+"'"+ name +"'"+ ")");

               //get return value from javascript
               msg = (String)webEngine.executeScript("hello()");

               printMsg(msg);
            }
        });

        StackPane root = new StackPane();     
        root.getChildren().add(btn);          
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

    public void printMsg(String s){
        System.out.println(s);
    }
}

的JavaScript

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <script>
            var me    
            function hello(){
                return me;
            }
            function myName(name){
                me = name;
            }         
        </script>
    </body>
</html>

0 个答案:

没有答案