我有一个简单的 Applet 类:
package com.myapp;
class MyApplet extends Applet {
public String myMethod() {
return "Hello";
}
}
我已将我的 java 类与其他 java 类一起编译成 jarfile。然后我运行这个 jar 文件主类以确保正确创建 jar。它有效。
然后我尝试将此 Applet 嵌入到我的页面中:
<script type="application/javascript">
$(document).ready(function () {
console.log(document.MyApplet.myMethod())
});
</script>
<applet archive="myjar.jar" code="com.myapp.MyApplet.class" id="MyApplet" name="MyApplet" width=100 height=100></applet>
这引发了我这个错误:
Uncaught TypeError: Cannot read property 'myMethod' of undefined
这意味着document.MyApplet
返回undefined
当我尝试这样调用它时:
document.getElementById('MyApplet').myMethod();
它给了我这个:
Uncaught TypeError: document.getElementById(...).myMethod is not a function
我错过了什么吗?
我已经对此进行了测试:
- Chrome 57.0.2987.133(64 位)
- Firefox 52.0.2(32 位)
Applet 使用 JDK 8
编译。
最佳答案
尝试
console.log(document.getElementById('MyApplet').myMethod())
可以通过getElementById
抓取元素
根据docs您需要包含以下脚本来运行小程序。
<script src=
"https://www.java.com/js/deployJava.js"></script>
<script>
<!-- applet id can be used to get a reference to
the applet object -->
var attributes = { id:'MyApplet',
code:'jcom.myapp.MyApplet.class', width:1, height:1} ;
var parameters = { jnlp_href: 'MyApplet.jnlp'} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
关于Javascript,调用 Java Applet 方法抛出 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43425809/