Reputation: 366
I am trying to create a very simple java Applet to try out using Java functions in a web browser. problem is, is that I can't get any sort of functionality from my applet. I've tried dozens of tutorials and answers from within this site, but nothing produces any different result, The browser always says AppName.FunctionName is not a function.
Here is my html...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Test Applet</title>
</head>
<body onload="test()">
<applet code="TestApplet.class" name="AppTest"
height="350" width="100"></applet>
<script language="Javascript">
function test(){
alert("Attempt 1");
var elem= document.getElementById('AppTest');
alert(elem);
elem.test();
alert("Attempt 2");
document.AppTest.test();
}
</script><br>
</body>
</html>
and here is my Java code...
import javax.swing.JApplet;
public class TestApplet extends JApplet {
public String sayHi(){
return "hello";
}
public void test(){
System.out.println("You did it bro");
}
}
Any ideas why this seems to do nothing? Note: I am testing it using FireFox
EDIT:
So trying to move closer to a working solution, I modified my html as follows
<html>
<head>
<title>Test Applet</title>
</head>
<body>
<applet code="AppPack.TestApplet.class"
codebase="TestApplet.jar" name="AppTest"
scriptable="true" height="350" width="100"></applet>
<script language="Javascript">function test(){
document.AppTest.test();
}
</script><br>
<input name="tryit" value="TryIt" onclick="test()"
type="button">
</body>
</html>
I've tried to use the codebase declaration, seeing as how including it draws the applet to the canvas, however the box just contains an error saying class not found exception, and without it I get a blank page with just the button. ALL the files are in the same directory, and if I test the applet in eclipse, it generates html to run the applet in the viewer, but these html files also don't load if opened simply using a broswer. Please, can anyone shed some light on what I am doing wrong?
Upvotes: 0
Views: 2069
Reputation: 168845
The test function is called too soon.
An applet won't necessarily be loaded and started by the time the page onload
function is called. That really only means that the browser has read all the HTML related to the page, not necessarily images, (externally defined) styles or scripts, or things that might be created as a result of the page loading (e.g. the applet).
Put the call to the test()
method into a button that you click, wait 'a few moments' after page load, and try it again.
Also be sure to declare it scriptable='true'
when deploying. Like this:
<applet
code="TestApplet"
name="AppTest"
scriptable="true"
height="350"
width="100">
</applet>
Most browsers will allow an applet to be called without it, but best to add it for the others.
Upvotes: 2