我的 Java Applet
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JApplet;
import javax.swing.JButton;
import netscape.javascript.JSObject;
@SuppressWarnings("serial")
public class LocalFileSystem extends JApplet {
private JSObject js;
private final JButton button;
public LocalFileSystem() {
setLayout(null);
button = new JButton("getDrives()");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button.setText( getDrives() );
}
});
button.setBounds(25, 72, 89, 23);
add(button);
}
public void init() {
js = JSObject.getWindow(this);
}
public String getDrives() {
if (js != null) return "NULL";
for (File f: File.listRoots())
js.call("addDrive", new String[] { f.getAbsolutePath() });
return "NOT NULL";
}
}
我的 HTML 代码:
<!-- language: lang-html --><html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function addDrive(s) {
alert(s);
}
</script>
<object type="application/x-java-applet;version=1.4.1" width="180"
height="180" name="jsap" id="applet">
<param name="archive" value="http://localhost/LocalFileSystemApplet/bin/applet.jar?v=<?php print mt_rand().time(); ?>">
<param name="code" value="LocalFileSystem.class">
<param name="mayscript" value="yes">
<param name="scriptable" value="true">
<param name="name" value="jsapplet">
</object>
</body>
</html>
小程序正在加载,当我按下按钮时,getDrives() 总是返回 NULL。 为什么?
最佳答案
根据模糊的内存,如果从 init()
方法调用建立 JSObject
的调用将会失败。
所以这个..
public void init() {
js = JSObject.getWindow(this);
}
..应该是..
public void start() {
js = JSObject.getWindow(this);
}
由于 start()
方法可能会被多次调用(例如,将浏览器从最小化状态恢复),因此使用检查可能是值得的:
public void start() {
if (js==null) {
js = JSObject.getWindow(this);
}
}
更新
我在Read/Write HTML field values from JAVA看到了.页面底部的“小字”注释:
For best result, never use LiveConnect JSObject in Applet's init() method.
关于Java Applet : Call JavaScript - JSObject. getWindow(this) 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6403131/