将字符串列表作为参数从本机 java 代码传递给 java 脚本函数

Passing a list of string as an argument to javascript function from native java code

我有一个java脚本函数:

drawPath: function drawPathFn(nodeList){
        console.log(""+nodeList[1]);
},

调用此函数的本机 java 代码是:

List<String> nodes = getShortestPath(s, d);
architectView.callJavascript("World.drawPath('"+nodes+"')");

nodes 列表充满了几个位置名称,但是当我尝试将此列表传递给 javascript 函数时,控制台输出只是:“[” for console.log(""+nodeList[0]); and "S" console.log(""+nodeList[1]);

我想要的是当我调用 nodeList[0] 时,我希望它打印出来,例如"Building A"。 我怎样才能做到这一点?

您需要在 javascript 中将 JSObject 或字符串作为文字数组传递,即 "['str0','str1']"。 以下是如何使用 JSObject:

//first we need an Iterator to iterate through the list
java.util.Iterator it = nodes.getIterator();
//we'll need the 'window' object to eval a js array, you may change this
//I dont know if you are using an applet or a javaFX app. 
netscape.javascript.JSObject jsArray = netscape.javascript.JSObject.getWindow(YourAppletInstance).eval("new Array()");
//now populate the array 
int index = 0;
while(it.hasNext()){
  jsArray.setSlot(index, (String)it.next());
  index++;
}
//finaly call your function
netscape.javascript.JSObject.getWindow(YourAppletInstance).call("World.drawPath",new Object[]{jsArray});

以下是使用文字字符串的方法:

java.util.Iterator it = nodes.getIterator();
int index = 0;
String literalJsArr = "[";
//populate the string with 'elem' and put a comma (,) after every element except the last 
while(it.hasNext()){
  literalJsArr += "'"+(String)it.next()+"'";
  if(it.hasNext() ) literalJsArr += ",";
  index++;
}
literalJsArr += "]"; 
architectView.callJavascript("World.drawPath("+literalJsArr+")");

参考:

http://www.oracle.com/webfolder/technetwork/java/plugin2/liveconnect/jsobject-javadoc/netscape/javascript/JSObject.html https://docs.oracle.com/javase/tutorial/deployment/applet/invokingJavaScriptFromApplet.html