由于这是我的第一篇文章,请原谅任何不准确之处。我的问题,我想在初始化方法
上将javascript函数的值传递给Javafxpublic void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
final URL urlGoogleMaps = getClass().getResource("googlemaps.html");
System.out.println("fjdsoij");
browser.getEngine().load(urlGoogleMaps.toExternalForm());
WebEngine webEngine = browser.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>(){
@Override
public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
if(newState == State.SUCCEEDED){
JSObject window = (JSObject)webEngine.executeScript("window");
window.setMember("app", new JavaApplication());
}
}
});
}
public class JavaApplication{
public void calljavascript( int lengthInMeters){
System.out.println(lengthInMeters);
}
}
}
和javascript部分就是这样
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(0, -180),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, 157.821856)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
//geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
var lengthInMeters = google.maps.geometry.spherical.computeLength(flightPath.getPath());
flightPath.setMap(map);
alert("polyline is "+lengthInMeters+" long");
app.calljavascript(lengthInMeters);
}
google.maps.event.addDomListener(window, 'load', initialize);
我想传递的值是方法calljavascript上的lengthInMeters有什么想法吗? thnx提前
答案 0 :(得分:0)
我尝试过代码的简化版本:
WebEngine webEngine = browser.getEngine();
webEngine.getLoadWorker().stateProperty().addListener((ov,oldState,newState)->{
if(newState==State.SUCCEEDED){
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("app", new JavaApplication());
}
});
webView.getEngine().loadContent("<html>\n"
+ " <script>function initialize() {"
+ " var lengthInMeters = 5; "
+ " app.calljavascript(lengthInMeters);"
+ "} </script> "
+ " <body onLoad=\"initialize()\">Hi!\n"
+ " </body>\n"
+ "</html>");
它没有用。
在您的情况下,在我的方法中,{<1}}在网页加载后被称为,因此setMember()
在之前被称为 initialize()
方法。因此,load
失败。
解决方案是:
app.calljavascript()
请注意,我们在加载网页内容之前设置了成员。
修改强>
我创建了一个更详细的答案here。