我正在学习一些 Java/JavaScript 编码,但我似乎碰壁了。我正在尝试将 agruments 从 Java 传递给 JavaScript,但无论我做什么“JSObject jso = JSObject.getWindow(this);” 总是抛出异常。我已经进行了一些搜索,但找不到任何解决方案。我从一个网站( http://www.codejava.net/java-se/applet/liveconnect-the-api-for-communication-between-java-applet-and-javascript )偷了下面的代码,但没有看到JavaScript 或 Java 中的任何错误,并且两个文件都能正确编译。
我已将 plugin.jar 添加到 buildpath 并确保 jfxrt.jar 不在构建路径中。我认为 jre7 中的 plugin.jar 可能有问题,所以我尝试了 jre6,但遇到了同样的错误。我正在使用的代码如下。
Java 代码:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;
public class TestApplet extends JApplet {
private JButton button = new JButton("Call Javascript");
private JLabel label = new JLabel();
public void init() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(button, BorderLayout.NORTH);
getContentPane().add(label, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Thread runner = new Thread(new Runnable() {
public void run() {
try {
testLiveConnect();
} catch (JSException jse) {
// Error
jse.printStackTrace();
}
}
});
runner.start();
}
});
}
private void testLiveConnect() throws JSException {
JSObject jso = JSObject.getWindow(this);
// call Javascript's method foo() with no argument
String result = (String) jso.call("foo", null);
label.setText(result);
// delay 2 seconds to see the result
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// call Javascript's method foo() with two arguments
result = (String) jso.call("bar", new String[] {"Alice", "Alisa"});
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// execute a Javascript expression
String expression = "alert('Hi, I am from Javascript.');";
jso.eval(expression);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of a named member from Javascript
result = (String) jso.getMember("coop");
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of an indexed member from Javascript
result = (String) jso.getSlot(1);
label.setText(result);
}
}
JavaScript 代码:
<html>
<head>
<title>LiveConnect - Java-Javascript communnication demo</title>
</head>
<body>
<center>
<applet id="testApplet"
code="TestApplet.class"
width="200" height="80"
>
</applet>
</center>
</body>
<script type="text/javascript">
var coop = "Ooops!";
this[1] = "Slot 1";
function foo() {
return "This is from foo()";
}
function bar(firstName, lastName) {
return "Greeting " + firstName + " " + lastName + "!";
}
</script>
</html>
抛出异常:
netscape.javascript.JSException
at netscape.javascript.JSObject.getWindow(Unknown Source)
at test.TestApplet.testLiveConnect(TestApplet.java:34)
at test.TestApplet.access$0(TestApplet.java:33)
at test.TestApplet$1$1.run(TestApplet.java:22)
at java.lang.Thread.run(Unknown Source)