Overview
Navigate User Interface topic:
|
A Java applet is an applet delivered in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Oracle's AppletViewer, a stand alone tool to test applets. Java applets were introduced in the first version of the Java language in 1995. Java applets are usually written in the Java programming language but they can also be written in other languages that compile to Java bytecode such as Jython.
Applets are used to provide interactive features to web applications that cannot be provided by HTML. Since Java's bytecode is platform independent, Java applets can be executed by browsers for many platforms, including Windows, Unix, Mac OS and Linux. There are open source tools like applet2app which can be used to convert an applet to a stand alone Java application/windows executable. This has the advantage of running a Java applet in off-line mode without the need for Internet browser software.
The First Applet
Applets are not constructed in the same way as other classes or main programs. Here is the basic code layout of an Applet:
Code listing 9.3: ClassName.java
|
Although other functions and methods allow for a more complex applet, this is the basic code layout of applets. Using both the methods init() and paint() are not necessary — only one is required — but they are the most commonly used methods in the creation of Java applets.
To put the applet in a web page, just add this line of code in the HTML page (width and height can be left away):
Code listing 9.4:
<applet code="ClassName.class" width=420 height=100></applet>
|
Of course, the compiled ClassName.java file should be in the corresponding directory on the server. There are recently some discussions about the usage of applet tag but it still truly can be recommended for beginning and also would work in the real world as well.
- See also applet markup.
The Applet Lifecycle
Four methods are called from the browser and can be extended from the Applet class: init() and destroy() are only called once, and start() and stop() are called as many times as the user visits the web page.
Code listing 9.5: MyApplet.java
|
Embedding the applet tag
The HTML applet tag can be embedded in the applet source code to allow 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:
Code section 9.10: MyApplet comment
|