Java - Applet Basics

JAVA - APPLET BASICS



Copyright ? tutorials

An applet is a Java program t hat runs in a Web browser. An applet can be a fully funct ional Java

applicat ion because it has t he ent ire Java API at it s disposal.

There are some import ant differences bet ween an applet and a st andalone Java applicat ion, including

t he following:

An applet is a Java class t hat ext ends t he java.applet .Applet class.

A main() met hod is not invoked on an applet , and an applet class will not define main().

Applet s are designed t o be embedded wit hin an HTML page.

When a user views an HTML page t hat cont ains an applet , t he code for t he applet is

downloaded t o t he user's machine.

A JVM is required t o view an applet . The JVM can be eit her a plug-in of t he Web browser or a

separat e runt ime environment .

The JVM on t he user's machine creat es an inst ance of t he applet class and invokes various

met hods during t he applet 's lifet ime.

Applet s have st rict securit y rules t hat are enforced by t he Web browser. The securit y of an

applet is oft en referred t o as sandbox securit y, comparing t he applet t o a child playing in a

sandbox wit h various rules t hat must be followed.

Ot her classes t hat t he applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet :

Four met hods in t he Applet class give you t he framework on which you build any serious applet :

init: This met hod is int ended for what ever init ializat ion is needed for your applet . It is called

aft er t he param t ags inside t he applet t ag have been processed.

start: This met hod is aut omat ically called aft er t he browser calls t he init met hod. It is also

called whenever t he user ret urns t o t he page cont aining t he applet aft er having gone off t o

ot her pages.

sto p: This met hod is aut omat ically called when t he user moves off t he page on which t he

applet sit s. It can, t herefore, be called repeat edly in t he same applet .

destro y: This met hod is only called when t he browser shut s down normally. Because applet s

are meant t o live on an HTML page, you should not normally leave resources behind aft er a user

leaves t he page t hat cont ains t he applet .

paint: Invoked immediat ely aft er t he st art () met hod, and also any t ime t he applet needs t o

repaint it self in t he browser. The paint () met hod is act ually inherit ed from t he java.awt .

A "Hello, World" Applet :

The following is a simple applet named HelloWorldApplet .java:

import java.applet.*;

import java.awt.*;

public class HelloWorldApplet extends Applet

{

public void paint (Graphics g)

{

g.drawString ("Hello World", 25, 50);

}

}

These import st at ement s bring t he classes int o t he scope of our applet class:

java.applet .Applet .

java.awt .Graphics.

Wit hout t hose import st at ement s, t he Java compiler would not recognize t he classes Applet and

Graphics, which t he applet class refers t o.

The Applet CLASS:

Every applet is an ext ension of t he java.applet.Applet class. The base Applet class provides

met hods t hat a derived Applet class may call t o obt ain informat ion and services from t he browser

cont ext .

These include met hods t hat do t he following:

Get applet paramet ers

Get t he net work locat ion of t he HTML file t hat cont ains t he applet

Get t he net work locat ion of t he applet class direct ory

Print a st at us message in t he browser

Fet ch an image

Fet ch an audio clip

Play an audio clip

Resize t he applet

Addit ionally, t he Applet class provides an int erface by which t he viewer or browser obt ains

informat ion about t he applet and cont rols t he applet 's execut ion. The viewer may:

request informat ion about t he aut hor, version and copyright of t he applet

request a descript ion of t he paramet ers t he applet recognizes

init ialize t he applet

dest roy t he applet

st art t he applet 's execut ion

st op t he applet 's execut ion

The Applet class provides default implement at ions of each of t hese met hods. Those

implement at ions may be overridden as necessary.

The "Hello, World" applet is complet e as it st ands. The only met hod overridden is t he paint met hod.

Invoking an Applet :

An applet may be invoked by embedding direct ives in an HTML file and viewing t he file t hrough an

applet viewer or Java-enabled browser.

The t ag is t he basis for embedding an applet in an HTML file. Below is an example t hat

invokes t he "Hello, World" applet :

The Hello, World Applet

If your browser was Java-enabled, a "Hello, World"

message would appear here.

Based on t he above examples, here is t he live applet example: Applet Example.

No te: You can refer t o HTML Applet Tag t o underst and more about calling applet from HTML.

The code at t ribut e of t he t ag is required. It specifies t he Applet class t o run. Widt h and

height are also required t o specify t he init ial size of t he panel in which an applet runs. The applet

direct ive must be closed wit h a t ag.

If an applet t akes paramet ers, values may be passed for t he paramet ers by adding t ags

bet ween and . The browser ignores t ext and ot her t ags bet ween t he applet

t ags.

Non-Java-enabled browsers do not process and . Therefore, anyt hing t hat

appears bet ween t he t ags, not relat ed t o t he applet , is visible in non-Java-enabled browsers.

The viewer or browser looks for t he compiled Java code at t he locat ion of t he document . To specify

ot herwise, use t he codebase at t ribut e of t he t ag as shown:

If an applet resides in a package ot her t han t he default , t he holding package must be specified in

t he code at t ribut e using t he period charact er (.) t o separat e package/class component s. For

example:

Get t ing Applet Paramet ers:

The following example demonst rat es how t o make an applet respond t o set up paramet ers specified

in t he document . This applet displays a checkerboard pat t ern of black and a second color.

The second color and t he size of each square may be specified as paramet ers t o t he applet wit hin

t he document .

CheckerApplet get s it s paramet ers in t he init () met hod. It may also get it s paramet ers in t he paint ()

met hod. However, get t ing t he values and saving t he set t ings once at t he st art of t he applet ,

inst ead of at every refresh, is convenient and efficient .

The applet viewer or browser calls t he init () met hod of each applet it runs. The viewer calls init ()

once, immediat ely aft er loading t he applet . (Applet .init () is implement ed t o do not hing.) Override t he

default implement at ion t o insert cust om init ializat ion code.

The Applet .get Paramet er() met hod fet ches a paramet er given t he paramet er's name (t he value of a

paramet er is always a st ring). If t he value is numeric or ot her non-charact er dat a, t he st ring must be

parsed.

The following is a skelet on of CheckerApplet .java:

import java.applet.*;

import java.awt.*;

public class CheckerApplet extends Applet

{

int squareSize = 50;// initialized to default size

public void init () {}

private void parseSquareSize (String param) {}

private Color parseColor (String param) {}

public void paint (Graphics g) {}

}

Here are CheckerApplet 's init () and privat e parseSquareSize() met hods:

public void init ()

{

String squareSizeParam = getParameter ("squareSize");

parseSquareSize (squareSizeParam);

String colorParam = getParameter ("color");

Color fg = parseColor (colorParam);

setBackground (Color.black);

setForeground (fg);

}

private void parseSquareSize (String param)

{

if (param == null) return;

try {

squareSize = Integer.parseInt (param);

}

catch (Exception e) {

// Let default value remain

}

}

The applet calls parseSquareSize() t o parse t he squareSize paramet er. parseSquareSize() calls t he

library met hod Int eger.parseInt (), which parses a st ring and ret urns an int eger. Int eger.parseInt ()

t hrows an except ion whenever it s argument is invalid.

Therefore, parseSquareSize() cat ches except ions, rat her t han allowing t he applet t o fail on bad

input .

The applet calls parseColor() t o parse t he color paramet er int o a Color value. parseColor() does a

series of st ring comparisons t o mat ch t he paramet er value t o t he name of a predefined color. You

need t o implement t hese met hods t o make t his applet works.

Specifying Applet Paramet ers:

The following is an example of an HTML file wit h a CheckerApplet embedded in it . The HTML file

specifies bot h paramet ers t o t he applet by means of t he t ag.

Checkerboard Applet

No te: Paramet er names are not case sensit ive.

Applicat ion Conversion t o Applet s:

It is easy t o convert a graphical Java applicat ion (t hat is, an applicat ion t hat uses t he AWT and t hat

you can st art wit h t he java program launcher) int o an applet t hat you can embed in a web page.

Here are t he specific st eps for convert ing an applicat ion t o an applet .

Make an HTML page wit h t he appropriat e t ag t o load t he applet code.

Supply a subclass of t he JApplet class. Make t his class public. Ot herwise, t he applet cannot be

loaded.

Eliminat e t he main met hod in t he applicat ion. Do not const ruct a frame window for t he

applicat ion. Your applicat ion will be displayed inside t he browser.

Move any init ializat ion code from t he frame window const ruct or t o t he init met hod of t he

applet . You don't need t o explicit ly const ruct t he applet object .t he browser inst ant iat es it for

you and calls t he init met hod.

Remove t he call t o set Size; for applet s, sizing is done wit h t he widt h and height paramet ers in

t he HTML file.

Remove t he call t o set Default CloseOperat ion. An applet cannot be closed; it t erminat es when

t he browser exit s.

If t he applicat ion calls set Tit le, eliminat e t he call t o t he met hod. Applet s cannot have t it le

bars. (You can, of course, t it le t he web page it self, using t he HTML t it le t ag.)

Don't call set Visible(t rue). The applet is displayed aut omat ically.

Event Handling:

Applet s inherit a group of event -handling met hods from t he Cont ainer class. The Cont ainer class

defines several met hods, such as processKeyEvent and processMouseEvent , for handling part icular

t ypes of event s, and t hen one cat ch-all met hod called processEvent .

In order t o react an event , an applet must override t he appropriat e event -specific met hod.

import

import

import

import

java.awt.event.MouseListener;

java.awt.event.MouseEvent;

java.applet.Applet;

java.awt.Graphics;

public class ExampleEventHandling extends Applet

implements MouseListener {

StringBuffer strBuffer;

public void init() {

addMouseListener(this);

strBuffer = new StringBuffer();

addItem("initializing the apple ");

}

public void start() {

addItem("starting the applet ");

}

public void stop() {

addItem("stopping the applet ");

}

public void destroy() {

addItem("unloading the applet");

}

void addItem(String word) {

System.out.println(word);

strBuffer.append(word);

repaint();

}

public void paint(Graphics g) {

//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0,

getWidth() - 1,

getHeight() - 1);

//display the string inside the rectangle.

g.drawString(strBuffer.toString(), 10, 20);

}

public

}

public

}

public

}

public

}

void mouseEntered(MouseEvent event) {

void mouseExited(MouseEvent event) {

void mousePressed(MouseEvent event) {

void mouseReleased(MouseEvent event) {

public void mouseClicked(MouseEvent event) {

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download