'JavaFx to Javascript. What is the proper way of passing parameters.
I am trying to learn how to use JavaFX and I don't know what is the proper way of passing a value to JS and returning a value from JS.
This code works fine, but I don't know if it is proper coding. If you have any suggestion on how to do it properly please tell me.
Thank you.
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
