如何从JavaScript调用applet中声明的方法 [英] How to call a method declared in an applet from 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>
加载页面时出现错误:
TypeError:对象#没有方法'openFile'
TypeError: Object # has no method 'openFile'
我该怎么做才能解决此错误并使Applet正常运行?
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直接调用小程序的公共方法或公共变量. JavaScript将嵌入式applet视为对象.通过为小程序提供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调用applet中声明的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!