Java applet: JavaScript call - 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">
    <param name="name" value="jsapplet">
</object>
</body>
</html>

      

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

+1


source to share


2 answers


From undefined memory, calls to set JSObject

will be out of order when the method is called init()

.

So this is ..

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

      

.. probably should be ..

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

      

Since the method start()

can be called many times (for example, restoring the browser from the bare minimum), it can pay to check:



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

      


Update

I saw this in Reading / Writing HTML Field Values ​​from JAVA . The "little stamp" at the bottom of the page notes:

For best results, never use JSbject LiveConnect in the init () method of Applet.

+3


source


Check out this line of code:

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

      



Must not be?:

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

      

+1


source







All Articles