【问题标题】:Java Applet: Call JavaScript - JSObject.getWindow(this) returns always nullJava Applet:调用 JavaScript - JSObject.getWindow(this) 始终返回 null
【发布时间】:2011-09-18 04:32:56
【问题描述】:

我的 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。 为什么?

【问题讨论】:

  • setLayout(null); 放弃所有希望,你们进入那里。为避免维护噩梦,使用布局。

标签: java javascript html applet call


【解决方案1】:

根据模糊的记忆,如果从 init() 方法调用建立 JSObject 的调用将失败。

所以这个..

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

..应该是..

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

由于start() 方法可能会被多次调用(例如,从最小化状态恢复浏览器),因此使用支票可能是值得的:

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

更新

我在Read/Write HTML field values from JAVA 看到它。页面底部的“小字”注释:

为获得最佳效果,切勿在 Applet 的 init() 方法中使用 LiveConnect JSObject。

【讨论】:

    【解决方案2】:

    检查这行代码:

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

    不应该吗?

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

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2015-08-15
      • 2012-03-18
      • 2016-11-04
      • 2016-07-28
      相关资源
      最近更新 更多