[英]How to call a method declared in an applet from JavaScript
我正在尝试制作一个基本的Java 小程序来为他们打开客户端计算机上的文件。 我想通过 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();
}
}
}
在我网页的正文标签之间,我有以下内容:
<applet code="Test.class" height="0" width="0"></applet>
<script type="text/javascript">
document.applets[0].openFile("C:\\test.log");
</script>
当我加载页面时,出现错误:
类型错误:对象 # 没有方法“openFile”
我需要做什么来修复此错误并使小程序正常工作?
采用:
<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 将嵌入的小程序视为一个对象。 通过为小程序提供 ID,JavaScript 可以通过以下方式访问它:
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>
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.