Java小程序:调用JavaScript - JSObject.getWindow(本)始终返回null [英] Java Applet: Call JavaScript - JSObject.getWindow(this) returns always null

查看:968
本文介绍了Java小程序:调用JavaScript - JSObject.getWindow(本)始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 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>

该小程序被加载,当我打的按钮,我总是getDrives得到NULL()返回。
为什么呢?

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

推荐答案

从模糊的记忆,来电以确定是否从 JSObject 将失败>的init()方法。

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:

为达到最佳效果,从不使用LiveConnect的JSObject在applet的init()方法。

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

这篇关于Java小程序:调用JavaScript - JSObject.getWindow(本)始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆