JavaFX 2.2在javascript和webview中进行双向通信 [英] JavaFX 2.2 bidirectional communication in javascript and webview
问题描述
我正在研究JavaFX 2.2,我正在使用webview将html代码集成到JavaFX场景中,并且能够正确加载html。我正在关注这个链接,并试图将一些对象从javascript传递到webview / controller但是我在java端获取空值。
I am working on JavaFX 2.2, I am using webview to integrate html code in the JavaFX scene and was able to load the html correctly. I was following this link and was trying to pass some objects from javascript to webview/controller but I am getting null values at java side.
我在JSObject中保存了一个接口对象,如下所示
I have saved a interface object in JSObject like below
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> ov,
State oldState, State newState) {
if (newState == State.SUCCEEDED) {
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", new JavaApp());
}
}
}
);
我创建了一个类
public class JavaApp {
public void exit() {
Platform.exit();
}
public void print(Date date) {
System.out.println("Parm:"+date);
}
public Date getValue() {
return new Date();
}
}
我的html是
<html lang="en">
<head>
<script type="text/javascript">
function callJava(){
app.print(new Date());
var val = app.getValue();
app.print(val);
}
</script>
</head>
<body>
<p>Help</p>
<p><a href="about:blank" onclick="callJava();">Exit the Application</a></p>
</body>
</html>
在上面的代码中,我总是得到在JavaApp.print()方法中打印的空值。有趣的是,当我在print方法中将参数从Date更改为String并从javascript传递字符串时,我得到了正确的值。
In above code I always get null values printed in JavaApp.print() method. Interesting point is when I changed the parameter from Date to String in print method and pass the string from javascript, I get correct values.
在这种情况下如何传输对象尤其是Date对象。任何帮助都很受欢迎
How I can transfer objects in this case especially Date object. Any help is much appritiated
推荐答案
Java 不知道日期
javascript 类。
您可以将 javascript 对象传递给 Java ,(你必须将它包装在 JSObject
中),但你只能直接得到这样的参数:
You can pass a javascript object to Java, ( you have to wrap it in a JSObject
) but you can get directly only parameters like these:
- 数字,
- 布尔,
- 字符串,
- 数组,
- 您拥有的同一个对象将放入javascript之前。
- Numbers,
- Boolean,
- String,
- arrays,
- The same object which you have put into javascript before.
我的解决方案:
public class JavaApp {
public void exit() {
Platform.exit();
}
//public void print(Date date) {
// System.out.println("Parm:"+date);
// }
public void print(long date) {
System.out.println("Parm:"+new Date(date));
}
public Date getValue() {
return new Date();
}
}
<html lang="en">
<head>
<script type="text/javascript">
function callJava(){
// app.print(new Date());
app.print(new Date().getTime());
var val = app.getValue();
app.print(val);
}
</script>
</head>
<body>
<p>Help</p>
<p><a href="about:blank" onclick="callJava();">Exit the Application</a></p>
</body>
</html>
这篇关于JavaFX 2.2在javascript和webview中进行双向通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!