Java小程序:调用JavaScript-JSObject.getWindow(this)总是返回null

Java Applet: Call JavaScript - JSObject.getWindow(this) returns always null

本文关键字:this null 返回 getWindow 程序 调用 JavaScript-JSObject Java      更新时间:2023-09-26

我的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()方法可能被调用多次(例如,从最小化状态恢复浏览器),因此使用check:可能是值得的

public void start() {
    if (js==null) {
        js = JSObject.getWindow(this);
    }
}

更新

我在JAVA的读/写HTML字段值中看到了它。页面底部的"小字"注释:

为了获得最佳效果,请不要在Applet的init()方法中使用LiveConnect JSObject。

检查这行代码:

if (js != null) return "NULL";

不是吗

if (js == null) return "NULL";