Writing Applets

errorhandleSoftware and s/w Development

Nov 18, 2013 (3 years and 6 months ago)

140 views

Writing Applets


Overview of Applets


Creating an Applet User Interface


Communicating with Other Programs


Understanding Applet Capabilities
and Restrictions


Finishing an Applet


Common Applet Problems (and Their
Solutions)

Base on :
The Java Tutorial


Object
-
Oriented Programming for the Internet


Overview of Applets


Every applet is implemented by
creating a subclass of the
Applet class
.


The following figure shows the
inheritance hierarchy of the
Applet
class
.


java.lang.Object


|


+
----
java.awt.Component


|


+
----
java.awt.Container


|


+
----
java.awt.Panel


|


+
----
java.applet.Applet

A Simple Applet


A
Simple Applet


import java.applet.Applet;

import java.awt.Graphics;


public class Simple extends Applet {


StringBuffer buffer;


public void
init()

{


buffer = new StringBuffer();


addItem("initializing... ");

}


public void
start(
) {


addItem("starting... ");

}


public void
stop()

{


addItem("stopping... ");

}


public void
destroy()

{


addItem("preparing for unloading...");

}


void addItem(String newWord) {


System.out.println(newWord);


buffer.append(newWord);


repaint(); //AWT.Component

}


public void paint(Graphics g) {


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


g.drawRect(0, 0, size().width
-

1, size().height
-

1);



//Draw the current string inside the rectangle.


g.drawString(buffer.toString(), 5, 15);


}


}

The Life Cycle of an Applet


Loading the Applet


When an
applet is loaded, here's what
happens:


An
instance

of the applet's controlling
class (an Applet subclass) is created.


The applet initializes itself.


The applet starts running.


The Life Cycle of an Applet


Leaving and Returning to the Applet's
Page


When the user
leaves

the page, the applet
has the
option of stopping

itself.


When the user returns to the page, the
applet can start itself again.


The same sequence occurs when the user
iconifies and then reopens the window that
contains the apple.


The Life Cycle of an Applet


Reloading the Applet


Some browsers let the user
reload

applets,
which consists of unloading the applet and
then loading it again.


Before an applet is unloaded, it's given the
chance to stop itself and then to perform a
final cleanup
, so that the applet can release
any resources it holds.


After that, the applet is unloaded and then
loaded again.

The Life Cycle of an Applet


Quitting the Browser


When the user
quits

the browser, the applet
has the chance to stop itself and do final
cleanup before the browser exits.


Summary
-

An applet can react to major
events in the following ways:


It can
initialize

itself.


It can
start

running.


It can
stop

running.


It can perform a
final

cleanup
, in
preparation for being unloaded.

Methods for Milestones


init()





To initialize the applet each time it's
loaded (or reloaded).


The
init()

class is useful for one
-
time
initialization that doesn't take very
long.


In general, the
init()

method should
contain the code that you would
normally put into a constructor.

Methods for Milestones



start()





To start the applet's execution, such as
when the applet's loaded or when the user
revisits a page that contains the applet.


Every applet that does something after
initialization (except in direct response to
user actions) must override the
start()

method.


The
start()

method either performs the
applet's work or (more likely) starts up one
or more threads to perform the work.


Methods for Milestones


stop()





To stop the applet's execution, such as
when the user leaves the applet's page or
quits the browser.


Most applets that override
start()

should
also override the
stop()

method.


The
stop()

method should suspend the
applet's execution, so that it doesn't take
up system resources when the user isn't
viewing the applet's page.

Methods for Milestones


destroy()




To perform a final cleanup in preparation
for unloading.


Many applets don't need to override the
destroy()

method, since their
stop()

method
(which is called before
destroy()
) does
everything necessary to shut down the
applet's execution.


However,
destroy()

is available for applets
that need to release additional resources

Methods for Drawing
and Event Handling


There are two display methods that
applets can override:


paint()



The basic display method. Many applets
implement the paint() method to draw the
applet's representation within a browser
page.


update()



A method you can use along with
paint()

to
improve drawing performance.

Methods for Drawing
and Event Handling


Applets inherit their
paint()

and
update()

methods from the
Applet

class
, which inherits them from
the
Abstract

Window

Toolkit

(
AWT
)
Component class.


class Simple extends Applet {


. . .


public void paint(Graphics g) { . . . }



. . .


}

Methods for Drawing
and Event Handling


From the Component class, applets
inherit a group of methods for event
handling.


The Component class defines several
methods (such as
mouseDown()

and
action()
) for handling particular types of
events, and then one catch
-
all method,
handleEvent()
.



Methods for Drawing
and Event Handling


To react to an event, an applet must
override either the handleEvent()
method or the appropriate specialized
method.


For example, adding the following code
to the Simple applet makes it respond
to mouse clicks.


import java.awt.Event;

. . .

public boolean mouseDown(Event event, int x, int y) {


addItem("click!... ");


return true;

}

Methods for Adding UI
Components


The AWT supplies the following UI
components :


Buttons

(java.awt.Button)


Checkboxes

(java.awt.Checkbox)


Single
-
line text fields

(java.awt.TextField)


Larger text display and editing areas

(java.awt.TextArea)


Labels

(java.awt.Label)


Lists

(java.awt.List)


Pop
-
up lists of choices

(java.awt.Choice)


Sliders and scrollbars

(java.awt.Scrollbar)


Drawing

areas

(java.awt.Canvas)


Menus

(java.awt.Menu, java.awt.MenuItem,
java.awt.CheckboxMenuItem)


Containers

(java.awt.Panel,
java.awt.Window and its subclasses)

Methods for Using UI
Components in Applets


The
Applet class

inherits from the AWT
Container class, it's easy to add
components to applets and to use
layout managers to control the their
onscreen positions. Some of the
Container methods an applet can use:


add()



Adds the specified Component.


remove()



Removes the specified Component.


setLayout()



Sets the layout manager.

Adding a Non
-
Editable
Text Field to an Applet


To make the Simple applet use a
scrolling, non
-
editable

text field, we
can use the
TextField

class.


Here is the revised
source

code
.


The revised
init()

method creates an
uneditable text field (a TextField
instance).


It sets the applet's
layout manager

to
one that makes the text field as wide
as possible and then adds the text field
to the applet.

Threads in Applets


A
thread

--

sometimes known as an
execution

context

or a
lightweight

process

--

is a single sequential flow of
control
within a process
.


Even the simplest applets run in
multiple threads, although it's not
always apparent.


Many applets create and use their own
threads, so that they perform well
without affecting the performance of
the application they run in or of other
applets.

Threads in Applets


Every applet can run in multiple threads.


Applet drawing methods (
paint()

and
update()
) are always called from the
AWT drawing and event handling thread.


The threads from which the major
milestone methods
--

init(), start(), stop(),
and destroy()
--

are called depends on
the application that's running the applet.

Threads in Applets



PrintThread

is a modified version
of SimpleApplet that prints the
thread and thread group that its
init()
,
start
()
,
stop
()
,
destroy
()
, and
update
()

methods are called from.

Threads in Applets


Rule of Thumb
: An applet performing a
time
-
consuming

task should create and
use its own thread to perform that task.


Applets typically perform two kinds of
time
-
consuming tasks:
tasks that they
perform once
, and
tasks that they
perform repeatedly
.


Threads in Applets:
Examples


The first applet,
AnimatorApplet
,
shows how to use a thread to
perform
repeated tasks
.


The second applet,
SoundExample
,
shows how to use threads for
one
-
time initialization tasks
.

Using a Thread to
Perform Repeated Tasks


Applets typically create threads for
repetitive tasks in the applet
start()

method.


Creating the thread there makes it easy
for the applet to stop the thread when
the user leaves the page.


All you need to do is implement the
stop()

method so that it stops the
applet's thread. An
Animator example

Using a Thread to
Perform Repeated Tasks

public void start() {


if (frozen) {


//Do nothing. The user has requested that we


//stop changing the image.


} else {



//Start animating!



if (animatorThread == null) {



animatorThread = new Thread(
this
);



}


animatorThread.start();


}

}


public void stop() {


animatorThread = null;

}

Click Here to see the source

No garbage collect on this.

Using a Thread to Perform
One
-
Time Initialization


If an applet needs to perform some
initialization task that can take a while,
it should consider performing the
initialization in a thread.


For example, anything that requires
making a network connection should
generally be done in a background
thread.

Using a Thread to Perform
One
-
Time Initialization


Fortunately,
GIF

and
JPEG

image
loading is automatically done in the
background (using threads that you
don't need to worry about).


Sound

loading unfortunately, is not
guaranteed to be done in the
background.


The Applet
getAudioClip

methods don't
return until they've loaded all the audio
data.

Using a Thread to Perform
One
-
Time Initialization


SoundExample adheres closely to
the model presented in
Synchronizing Threads.


The producer:
SoundLoader
, a Thread
subclass.


The consumer:
SoundExample
, an
Applet subclass.


The storage object:
SoundList
, a
Hashtable subclass.

What Applets Can and
Can't Do


For
security

reasons, applets that are
loaded over the network have several
restrictions.


One is that an applet
can't ordinarily
read or write files

on the computer that
it's executing on.


Another is that an
applet can't make
network connections except to the
host that it came from
.

Security Restrictions


Current browsers impose the following
restrictions on any applet that's loaded
over the network:


An applet can't load libraries or define
native methods
.


It can't ordinarily
read

or
write

files on the
host that's executing it.


It can't make network connections except
to the host that it came from.

Security Restrictions


Current browsers impose the following
restrictions on any applet that's loaded
over the network:


It can't start any program on the host that's
executing it.


It can't read certain system properties.


Windows that an applet brings up look
different than windows that an application
brings up.


Security Restrictions


Every browser implements
security

policies

to keep applets from doing
damage.


Each browser has a
SecurityManager
object that implements its security
policies.


When a
SecurityManager

detects a
violation, it throws a
SecurityException
.


Your applet can catch this
SecurityException

and react
appropriately.

Applet Capabilities


The java.applet package provides an
API that gives applets some capabilities
that applications don't have:


Applets can make network connections to
the host they came from.


Applets running within a Web browser can
easily cause HTML documents to be
displayed.


Applets can invoke public methods of other
applets on the same page.

Applet Capabilities


The java.applet package provides an
API that gives applets some capabilities
that applications don't have:


Applets that are loaded from the local file
system (from a directory in the user's
CLASSPATH) have none of the restrictions
that applets loaded over the network do.


Although most applets stop running once
you leave their page, they don't have to
.


Adding an Applet to an
HTML Page


Here's the simplest form of the
<APPLET> tag:


<APPLET
CODE=AppletSubclass.class
WIDTH=anInt HEIGHT=anInt>

</APPLET>

Specifying the Applet
Directory with CODEBASE


Add a CODEBASE attribute to tell the
browser/viewer which directory the
Applet subclass bytecodes are in.

<APPLET CODE=AppletSubclass.class
CODEBASE=aURL WIDTH=anInt
HEIGHT=anInt>

</APPLET>


By making
aURL

an
absolute

URL
, you
can make a document loaded from your
HTTP server run an applet from another
HTTP server.


When
aURL

is a relative
URL
…..

Specifying Parameters
with the <PARAM> Tag


You can customize the applet's
configuration with parameters. For
example, you can set a button's text by
specifying the value of a parameter
named BUTTONTEXT.


Note that <PARAM> tags must appear
between the <APPLET> and </APPLET>
tags for the applet they affect.

Specifying Parameters
with the <PARAM> Tag

<APPLET CODE=AppletSubclass.class
WIDTH=anInt HEIGHT=anInt>

<PARAM NAME=parameter1Name VALUE=aValue>

<PARAM NAME=parameter2Name
VALUE=anotherValue>

</APPLET>



<applet code=AppletButton.class
codebase=example width=350 height=60>

<param name=windowType value=BorderWindow>

<param name=windowText value="BorderLayout">

<param name=buttonText value="Click here to see
a BorderLayout in action">

. . .

</applet>

Specifying Text to be Displayed
by Java
-
Deficient Browsers

<applet code=AppletButton.class codebase=example width=350
height=60>

<param name=windowType value=BorderWindow>

<param name=windowText value="BorderLayout">

<param name=buttonText value="Click here to see a
BorderLayout in action">

<blockquote>

<hr>

<em>Your browser can't run 1.0 Java applets, so here's a picture
of the window the program brings up:

</em>

<p>

<img src=images/BorderEx1.gif width=302 height=138>

<hr>

</blockquote>

</applet>