开发者

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

My 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";
}
}

My HTML Code:

<!-- 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"开发者_如何学Python>
    <param name="name" value="jsapplet">
</object>
</body>
</html>

The applet is being loaded and when I hit the button I always get NULL returned by getDrives(). Why?


From vague memory, calls to establish the JSObject will fail if called from the init() method.

So this..

public void init() {
    js = JSObject.getWindow(this);
}

..should probably be ..

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

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);
    }
}

Update

I saw it in Read/Write HTML field values from JAVA. The 'small print' at the bottom of the page notes:

For best result, never use LiveConnect JSObject in Applet's init() method.


Check this line of code:

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

Shouldn't that be?:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜