如何从 JavaScript 调用小程序中声明的方法 [英] How to call a method declared in an applet from JavaScript

查看:31
本文介绍了如何从 JavaScript 调用小程序中声明的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个基本的 Java 小程序 来打开客户端计算机上的文件为他们.我想通过JavaScript调用下面Java小程序中的openFile函数.

I am trying to make a basic Java applet to open a file on the client's computer for them. I would like to call the openFile function in the Java applet below via JavaScript.

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import javax.swing.JApplet;

public class Test extends JApplet {
    public void openFile(String filePath) {
        File f = new File(filePath);

        try {
            Desktop.getDesktop().open(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在我网页的正文标签之间,我有以下内容:

In between the body tags of my webpage I have the following:

<applet code="Test.class" height="0" width="0"></applet>

<script type="text/javascript">
    document.applets[0].openFile("C:\\test.log");
</script>

当我加载页面时出现错误:

When I load the page I get the error:

TypeError: Object # 没有方法 'openFile'

TypeError: Object # has no method 'openFile'

我需要做什么来修复这个错误并使小程序正常工作?

What do I need to do to fix this error and get the applet working?

推荐答案

使用:

<script src=
  "http://www.java.com/js/deployJava.js"></script>

<script>
    <!-- The applet id can be used to get a reference to
    the applet object -->
    var attributes = { id:'mathApplet',
        code:'jstojava.MathApplet',  width:1, height:1};
    var parameters = {jnlp_href: 'math-applet.jnlp'};
    deployJava.runApplet(attributes, parameters, '1.6');
</script>

参考:从 JavaScript 调用 Applet 方法

JavaScript 允许直接调用小程序的公共方法或公共变量.JavaScript 将嵌入的小程序视为一个对象.通过为小程序提供 ID,JavaScript 可以通过以下方式访问它:

JavaScript is allowed to directly call the applet’s public methods or public variables. JavaScript considers the embedded applet as an object. By providing the applet with an ID, JavaScript can access it with:

    document.Applet_ID.Applet_Method()

你可以使用这个,

<html>
<head>
    <script language="Javascript">
        function accessAppletMethod()
        {
            document.getElementById("AppletABC").appendText("Applet Method");
        }
    </script>

    <title>Testing</title>
</head>

<body onload="accessAppletMethod()">

    <h1>Javascript acess Applet method</h1>

    <applet width=300 height=100 id="AppletABC"
        code="JavaScriptToJava.class">
    </applet>
</body>

</html>

文件 JavaScriptToJava.java

import java.applet.Applet;
import java.awt.FlowLayout;
import java.awt.TextArea;

public class JavaScriptToJava extends Applet{

    TextArea textBox;

    public void init(){
        setLayout(new FlowLayout());
        textBox = new TextArea(5, 40);
        add(textBox);
    }

    public void appendText(String text){
        textBox.append(text);
    }
}

这篇关于如何从 JavaScript 调用小程序中声明的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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