Applets

  • Java code that runs in a web browser, in a designated display area
  • Init and destroy are only called once, but start and stop are called as many times as the user visits the web page.
// MyApplet.java

import java.applet.*;
import java.awt.*;

public class MyApplet extends Applet {
Applet.init() {...} // Called when the browser first loads the applet.
Applet.destroy() {...} // Called when the user quits the browser.
Applet.start(){...} // Called when the applet starts running.
Applet.stop() {...} // Called when the user leaves the web page,
// reloads it, or quits the browser.
}
<!-- MyApplet.html -->
...
<applet code="MyApplet" width=200 height=200>
</applet>
...

Embedding the applet tag

  • The HTML applet tag can be embedded in the applet source code.
  • Inclusion of the applet tag allows the applet to be run directly by a simple applet viewer, without the need for an .html file.
  • Typically, the applet tag immediately follows the import statements.
  • It must be enclosed by /* */ comments.
// MyApplet.java
...
/*
<applet code="MyApplet" width="200" height="200">
</applet>
*/
...

Hello, world!

// Hello.java 

import java.applet.*;
import java.awt.*;

public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);
}
}
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" width=200 height=200>
</applet>
</body>
</html>