Subclassed from java.applet.Applet
or javax.swing.JApplet
, applets are designed to be run embedded within other applications, particularly web browsers. Methods to override:
init ()
- called (by the browser) when applet is loaded, to initialise itdestroy ()
- called when applet is about to be unloaded from the browser, to free any resourcesstart ()
- called when the applet becomes visible. Often used with animation and threadsstop ()
- called when the applet temporarily becomes invisible (eg, the web page has scrolled). Stops performing animation etcgetAppletInfo ()
- called to get info about the applet. Returns string suitable for display in a dialogue boxgetParameter Info ()
- returns info about the parameters the applet can use
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello world!", 25, 50);
}
} // HelloWorld
<applet code="HelloWorld.class" width="150" height="100">
You get this text if Java cannot be run
</applet>
More generally:
<applet code="applet-filename"
width="pixel-width" height="pixel-height"
archive="jar-file-list" codebase="applet-url"
alt="alternate-text" name="applet-name">
<param name="param-name1" value="param-value1" />
<param name="param-name2" value="param-value2" />
<!-- however many parameters the applet can use -->
You get this text if Java cannot be run
</applet>
Recall that Java archive files are zipped files that contain classes plus images and other media assets.
Create with the utility jar which comes with the JDK. Eg:
jar cf myapplet.jar *.class *.gif
collects all classes and GIF images from current directory. Can then specify as the archive attribute in the HTML <applet> tag. You still need the code attribute to give a starting point.
JAR files are used widely as a means of distributing packages, classes, etc, including for uploading them to web servers. Ie, not just for applets.
From the outset, applets were quite restricted in what they could do, for secure use on the web.
Applets can be digitally signed so that they can be trusted. JDK utility jarsigner
can do this.
An unsigned applet downloaded by a browser cannot read files, list directories, look at any attributes of files, modify or delete files, create or accept a network connection to any computer other than the one from which it was loaded, listen for network connections, exit the JVM by calling System.exit () etc, spawn new processes, load native code libraries, initiate printing, access the system clipboard or event queue, read most system properties, etc.
Applets loaded from the local file system are assumed to be more trustworthy and so are less constrained.