Java Programming/Applets/Overview

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

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 Sun'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 offline mode without the need for internet browser software.

Source: Wikipedia

[edit] The Basic Applet

Applets are not constructed in the same way as other classes or main programs. Here is the basic code layout of an Applet:

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

public class ClassName extends Applet 
{
 <variable initializations>
 public void init() 
 {
  <style/layout>
 }
 
 public void paint(Graphics g) 
 {
  <graphics>
 }
}

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 (width and height can be left away):

 <applet code="ClassName.class" width=420 height=100></applet>

Of course, the compiled ClassName.java file should be in the corresponding directory.