javascript 如何从javascript调用applet中声明的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14016972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call method declared in applet from javascript
提问by Daniel
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.
我正在尝试制作一个基本的 Java Applet 来为他们打开客户端计算机上的文件。我想通过javascript调用下面java小程序中的openFile函数。
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 # has no method 'openFile'
类型错误:对象 # 没有方法“openFile”
Does anyone know what I need to do to fix this error and get the applet working?
有谁知道我需要做什么来修复这个错误并使小程序正常工作?
回答by Ravi
<script src=
"http://www.java.com/js/deployJava.js"></script>
<script>
<!-- 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>
Reference : Invoking Applet Methods From JavaScript
Update
更新
Javascript is allowed to directly call 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
Javascript 可以直接调用Applet 的公共方法或公共变量。Javascript 将嵌入的 Applet 视为一个对象。通过为 Applet 提供一个 ID,Javascript 可以访问它
document.Applet_ID.Applet_Method()
and you can use this,
你可以使用这个,
MyApplet.html
我的Applet.html
<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
JavaScript到Java.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);
}
}