Java Applet:调用 JavaScript - JSObject.getWindow(this) 总是返回 null [英] Java Applet: Call JavaScript - JSObject.getWindow(this) returns always null
问题描述
我的 Java 小程序
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.为什么?
The applet is being loaded and when I hit the button I always get NULL returned by getDrives(). Why?
推荐答案
从模糊的记忆来看,如果从 init()
方法调用建立 JSObject
将失败.
From vague memory, calls to establish the JSObject
will fail if called from the init()
method.
所以这个..
public void init() {
js = JSObject.getWindow(this);
}
..应该是..
public void start() {
js = JSObject.getWindow(this);
}
由于 start()
方法可能会被多次调用(例如,从最小化状态恢复浏览器),因此可能需要使用检查:
Since the start()
method might be called many times (e.g. restoring the browser from minimized), it might pay to use a check:
public void start() {
if (js==null) {
js = JSObject.getWindow(this);
}
}
更新
我在 从 JAVA 读取/写入 HTML 字段值 中看到了它.页面底部的小字"注释:
Update
I saw it in Read/Write HTML field values from JAVA. The 'small print' at the bottom of the page notes:
为获得最佳结果,切勿在 Applet 的 init() 方法中使用 LiveConnect JSObject.
For best result, never use LiveConnect JSObject in Applet's init() method.
这篇关于Java Applet:调用 JavaScript - JSObject.getWindow(this) 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!