references:
'HTML and Applets', 'Java 1.1
Certification Guide', Heller&Roberts and 'Just Java' P.van der Linden
Java programs can be run in different contexts. Up to now we have been
running stand-alone
programs from the command line. Some java programs run in another java
program's context.
For instance a web browser can have a java virtual machine running
in which a special kind
of java program called an applet can
be run. Because an applet is designed to plug into the
browser's java runtime environment, it has a different form and syntax
than a standalone java
application.
An applet is a java visual component.
It is referenced by
the browser from an applet
tag placed
in a HTML page. The info in the tag tells the browser where to find the
java
class file containing the applet. The browser
runs the java class code and places the applet
visually inside this HTML page.
This approach is very successful and is used with
two other java appliances, servlets and
enterprise javabeans.
They also run in the context of hosting applications. In the case of
servlets, they are run in a webserver application
on a server machine. Enterprise java beans
also run on a server in an application called
simply a container.
HTML
First it is neccessary to become familiar with the HTML page from where
a browser will
reference an applet. The page will be coded in HTML. Hypertext
Markup Language is
a page description language that provides instructions in the form
of Tags.
The
browser
interprets these tags to format it's presentation which might include
multimedia content such
as sound and images. Java-enabled browsers support applets which are
set in a html page
using the applet tag. Html tags
are not case sensitive. The following example uses the
convention where all the tags are set to upper case. The APPLET tags
must appear
somewhere within the BODY tags.
Notice future versions of HTML will deprecate the applet tag in favor
of the OBJECT tag.
( See table below ) Applet tags attributes list is basically a subset
of the larger and more
generic attribute list supported by the Object tag. So we'll continue
with a look at the Applet
tag noting as we go in small italics how the attribute tags compare
in the Applet and Object
as described in the W3C recommendation.
Plans to deprecate Applet Tag in favor of Object
Tag
Life has become a complicated with a W3C recommendation to deprecate the applet tag in the HTML 4 specification. It will be replaced by the Object tag. The good news is that Object tag is really not any harder to use than the applet tag and for the most part simply requires a substitution. Also many of the attributes supported in the new format are the same as we find in the applet tag. The browsers currently support both tags and probably will for a long time to come. It is probably wise to be conversant with both tag formats with the recognition that the applet tag is on it's way out. I successfully viewed an applet referenced from the Object tag in both Netscape v.4.7 and Explorer 5.0. The appletviewer utility didn't mind the Object tag but insisted on seeing the applet class referenced from a code tag. Also interesting to note, the new W3C rec indicates that the code tag can reference a class as an absolute or relative path. This is not the case with the current deployment of the code attribute tag in the Applet tag. Following is an example from the W3C recommendation showing how an applet tag might be replaced by the Object tag. // In the following example,
the APPLET element includes a Java applet in the document.
<APPLET code="Bubbles.class" width="500" height="500">
<OBJECT codetype="application/java"
To see the part of the document that pertains to
applets go to ObjectTag.html.
|
HTML tags of a typical page
< HTML > [ NAME ]
< HEAD >
< TITLE > An Applet </
TITLE >
< /HEAD >
<BODY>
// applet tags must appear somewhere between
body tags
< H1 >
Here's a little
text about this applet
< /H1 >
< BR >
< APPLET
CODE = Apt.class WIDTH = 200 HEIGHT = 150 >
</ APPLET >
</ BODY >
</ HTML >
// In this example the Applet class file must reside in the same directory as the Web page.
This example shows the tags that describe the
minimal html required to show an
applet on a page
<HTML>
<BODY>
<APPLET CODE=Zapplet.class
WIDTH=100
HEIGHT=100>
</APPLET>
</BODY>
</HTML>
A lot of the general functionality of HTML is available for use within
the APPLET tag
as shown in the detailed example below.
Detailed Applet Tag
<APPLET
CODE = class file (file or URL)
HEIGHT = pixels
WIDTH = pixels
[ CODEBASE = URL
directory ]
// [ ] square brackets indicate optional tags
[ ALT = alternate
text message ]
[ ARCHIVE = names
of JAR files ]
[ ALIGN = alignment
]
[ NAME = name for
other applets on page ]
[ HSPACE = pixel
]
[ VSPACE = pixel
]
> // notice all these instructions are enclosed withing the first applet tag
[ < PARAM NAME
= identifier VALUE = value > ]
[ < PARAM NAME
= identifier VALUE = value > ]
. . . . . . . . ..
[alternate HTML ]
</ APPLET > // CODE WIDTH and HEIGTH tags are mandatory
// Van der Linden notes that
there is a proposal to replace the java-specific applet tag with
// a more generic
EMBED tag but for now the applet tag is alive and well.(Aug 2000)
Following is a brief description of the tag options available in the
APPLET tag.
WIDTH & HEIGHT Tags
- specify the width and height of the applet in pixels
- other HTML page items may constrain the size of the applet
- getSize( ) will return at runtime how much space a
browser allots to an applet
Object tag'swidth and height
attribute tag per HTML 4 spec.recommnedation - This attribute specifies
the initial width and height
of the applet's display area (excluding any windows or dialogs that the
applet creates).
Note width and height the same in both tags
CODE & CODEBASE Tags
The applet code that will run in an HTML page is specified with the CODE tag.
Example Code="X.class"
// quotes can be left out on the class identifier but it is good HTML form to quote all attribute values
The CODEBASE tag is used to specify
an absolute path, a
URL, or a relative path
(relative to where the calling HTML file is located).
The
java class identifer is case
sensitive and must end with the .class extension.
Following are two handy methods for finding out
where the applet and the html page containing
it are located. getCodeBase(
) returns a URL describing the directory where the applet code
is located. getDocumentBase( )
returns a URL describing the directory where the HTML
page referencing the applet is located.
According to some texts CODE tag
is suppose to specifiable by a path relative to the calling
HTML or URL but this isn't the case. Try for yourself. Van der Linden gets it right and states that CODE must be provided as a single file name with no part of a longer path prefixed to it. |
// The W3C HTML 4 recommendation
has Object tag's code tag able to use absolute and relative paths
// where codebase will be restricted
to subdirectories of the directory containing the current document
// for security reasons. Note
this restriction doesn't exist at this time
Examples using the Codebase tag
In this example a HTML page is put in H2 directory, in H directory
in P directory. The
Applet code is put in C2 directory in C directory in P directory as
per Fig.1 Directory
Tree
Fig.1 DirectoryTree
P
Example 1 //
accessing by an absolute path
_|_ <applet
code="AppT.class" codebase="C:/P/C/C2" width="300" height="300">
</applet>
| |
H C Example
2 // accessing
by a path relative to the location of the calling HTML page
| | <applet
code="AppT.class" codebase="../../C/C2" width="300" height="300">
</applet>
H2 C2 Example 3 // accessing the applet using the url for a file on the local machine
<applet code="AppT.class" codebase="file:///c:/newcode/P/C/C2" width="300" height="300">
Example 4 //
using a url for an applet located on any Internet machine
<applet code="AppT.class" codebase="http://www.sentex.net/~pkomisar/C/C2"
width="90" height="90">
</applet>
PARAM Tag
PARAM tags appear between the <APPLET> param tags </APPLET>
This tag allows data to be passed from an HTML
page to an applet on that page.
The following applet example reads three parameters from the HTML page
and stores their
values in instance variables. Three parameters are specified in the
Applet tag All the values
are strings. Note quotes allow multiple words with spaces An applet
reading these values uses
the NAME identifiers as parameters
to the getParameter( ) method. (Going in, case is not
significant.) The string value returned, (representing the
VALUE assignment) however is
case sensitive.
Code examples from 'Java 1.1 Certification
Guide, Heller&Roberts
<APPLET CODE = Thermostat.class WIDTH = 200 HEIGHT = 200 > < PARAM NAME = label VALUE = "My Excellent Thermostat" > // note quotes allow inclusion of spaces < PARAM NAME = scale VALUE = celsius > < PARAM NAME = increment VALUE = 2 > </ APPLET > public class Thermostat extends Applet { private String label = "Thermo"; private boolean isCelsius = false; private int increment = 1; public void init( ) {
|
ALT Tag
The ALT tag provides an altenate text for browsers that know the tag but don't support applets.
1. < APPLET CODE = Thermostat.class WIDTH = 200
HEIGHT = 200
2. ALT = " Try another browser!" >
3. < /APPLET >
// alt is borrowed from
elsewhere in HTML in both the Object and Applet tags
HSPACE, VSPACE & ALIGN Tags
These tags control the applet position on the HTML page and the space
between them and
adjacent items on the page. HSPACE specifies the distance in
pixels between the applet's left
and right boundaries and any adjacent HTML elements. VSPACE
specifies
the distance in
pixels between the applet's top and bottom boundaries and any adjacent
HTML elements.
ALIGN values may be LEFT, RIGHT, BOTTOM, TOP, TEXTTOP, ABSBOTTOM,
ABSMIDDLE, MIDDLE, & BASELINE
example ALIGN="MIDDLE"
// align, hspace, vspace
are borrowed from elsewhere in HTML in both Object and Applet tags
NAME Tag
The Name tag can be used to support inter-applet communication. An applets
name can be
referenced by another applet on the same page to make method calls
on the named applet.
// Object tag's name attribute
per HTML 4 spec.recommnedation -This attribute specifies a name for
// the applet instance,
which makes it possible for applets on the same page to find (and communicate
// with) each other.
Note:same as for Applet tag
ARCHIVE Tag
A JAR (Java ARchive) file
is a zipped collection of files. The ARCHIVE tag identifies JAR
files on the server the browser needs to download. JAR's speed remote
class loading. Bundling
files in JARs reduce the per File download penalty to a single payment.
example // Note the CODE tag still identifies the class that starts execution, X.class is in the jar
<APPLET CODE = X.class WIDTH = 90 HEIGHT
= 60 ARCHIVE = "Zip_In.jar" >
< /APPLET >
Multiple JARs are downloaded using a comma-seperated list
<APPLET CODE=Apt.class WIDTH=100 HEIGHT=100
ARCHIVE=
a.jar, b.jar, n.jar">
< /APPLET >
// Object tag's archive attribute
tag per HTML 4 spec.recommnedation -This attribute specifies a
// comma-separated list of URIs
for archives containing classes and other resources that will be
// "preloaded". The classes
are loaded using an instance of an AppletClassLoader with the given
// codebase. Relative URIs for
archives are interpreted with respect to the applet's codebase.
// Preloading resources can
significantly improve the performance of applets. Note: same as Applet
object
This attribute names a resource containing a serialized representation
of an applet's state. It
is interpreted relative to the applet's codebase. The serialized data contains
the applet's class
name but not the implementation. The class name is used to retrieve the
implementation from
a class file or archive. ( see excerpt from W3C spec hyperlinked in the
table above)
Other relevant tags defined elsewhere in HTML
id, class
(document-wide
identifiers)
title(element
title)
style (inline
style information)
Applet class // Netscape 6.x supports swing!
When we talk about applets, we must now consider both the classic
Applet
class found in the
awt package and the newer JApplet
which
resides in the swing package. They
are different in
a few ways. Applet class has a
flow layout manager by default while JApplet's default layout
manager is as border layout.(See
box) JApplet has the more complex behaviour displayed by
JFrame, where menus and layered panes are used to show pop up menus
and tooltips. JApplet
like other swing components can have icons added. At this time you
cannot be assured of
widespread JVM support for swing components in the various browsers.
Accordingly
classic
Applet class may be a practical 'safe' choice
for current web programming usage.
(See Reminder below)
An applet is a visual component which is run in a browser. Applet
class
inherits
from Object,
Component,
Container and Panel. JApplet
in turn descends from Applet.
Applet class has
a few superficial similarities to Thread
class which can be a source of some confusion. For
instance the Thread class has a start( ) and
stop( ) method which starts and stops the thread.
Thread's stop( ) method has been deprecated
because
of trouble it causes (See box regarding
Thread class deprecations below). Applet's start(
) and stop( ) method are used in the context
of a browser entering and leaving a page in which
case the applet is started and stopped.
Stopping in the case of an applet amounts to
storing the applet with its current state in cache
memory in case the browser returns to the page
and expects everything still to be there.
JApplet has by default a BorderLayout
while Applet class has a FlowLayout by default inherited from Panel
Reminder
* FlowLayout manager adds components to a container from left to right, top to bottom. The components added retain their preferred size and shape. BorderLayout manager has NORTH, SOUTH, EAST, WEST and CENTER regions defined. Components added to North and South, keep their preferred height but width varies with the container. Components added to East and West areas keep their preferred width but height varies with the container. Default is CENTER and an add( ) to center in the absence of other zones being used will fill the screen. |
Methods of the Applet Life Cycle
public void init( ) | Called by the browser or appletviewer when an applet
is first
loaded into memory, overrridden to do one-time initializations and a good place to create a GUI and for starting threads. |
public void start( ) | After init( ) the browser/viewer calls start( ).
start( ) can be
overridden to start programmer defined threads. start( ) is called each time the browser visits the page |
public void paint(Graphics g) | Called by the system whenever the component needs
to be
redisplayed. paint( ) is overridden to change what appears on screen. |
public void stop( ) | Called when the browser leaves the applet's page |
When a web page containing an applet has been accessed, the applet class
is loaded into the
browser's runtime environment.The first method called is init(
) which performs the job of a
constructor in a regular java application. Next start(
) is called followed by paint( ) which
draws the graphical aspects of the applet. When the browser leaves
the page,
stop( ) is called
to shut down the applet and close any resources that may have been
associated with it.
// the applet is down but not
out, still cached in memory in case of a return to the page
Thread class method deprecations
Thread class' stop( ) method (as well as suspend( ) and resume( )) have been deprecated . stop( ) has been observed to be responsible for corrupting behaviour in a multi-threaded environment. (suspend( ) and resume( )'s lend themselves to the creation of deadlock. It is recommended that instead of calling stop( ) on a thread (from within an applet's stop( ) method, it is preferable to set the given thread to null.) For more info see 'the Java Tutorial',
|
Applet methods
// reference
void destroy( ) | Called by the browser to tell this applet it is
being reclaimed
and that it should destroy any resources that it has allocated. |
AppletContext
getAppletContext( ) |
Determines this applet's context, allowing the
applet to query
and affect the environment in which it runs. |
String getAppletInfo( ) | Returns information about this applet. |
AudioClip
getAudioClip(URL url) |
Returns the AudioClip object specified by the URL argument. |
AudioClip getAudioClip
(URL url, String name) |
Returns the AudioClip object specified by the URL and name arg |
URL getCodeBase( ) | Gets the base URL. |
URL getDocumentBase( ) | Gets the document URL. |
Image getImage(URL url) | Returns an Image object that can then be painted on the screen. |
Image getImage
(URL url, String name) |
Returns an Image object that can then be painted on the screen. |
Locale getLocale( ) | Gets the Locale for the applet, if it has been set. |
String getParameter
(String name) |
Returns the value of the named parameter in the HTML tag. |
String[][]
getParameterInfo( ) |
Returns info about parameters that are understood by this applet. |
void init( ) | Called by the browser or applet viewer to inform
this applet that it
has been loaded into the system. |
boolean isActive( ) | Determines if this applet is active. |
static AudioClip
newAudioClip(URL url) |
Get an audio clip from the given URL |
void play(URL url) | Plays the audio clip at the specified absolute URL. |
void play
(URL url, String name) |
Plays the audio clip given the URL and a specifier relative to it. |
void resize
(Dimension d) |
Requests that this applet be resized. |
void resize
(int width, int height) |
Requests that this applet be resized. |
void setStub
(AppletStub stub) |
Sets this applet's stub. |
void showStatus
(String msg) |
Requests this argument string be displayed in the "status window". |
void start() | Called by the browser or applet viewer to inform
this applet that
it should start its execution. |
void stop() | Called by the browser or applet viewer to inform
this applet that it
should stop its execution. |
A HelloWorld in swing
/* This is a basic HelloWorld applet with an extra line to make the font big */ import java.awt.*;
/* Putting the applet tag in
the source allows us to run the applet in applet viewer
// <applet code=OK.class width =400 height =100></applet> // note tags can be lower case public class OK extends JApplet{
|
A Fancier Applet example in classic AWT
/* This applet shows a couple of the drawing methods you can access from the Graphics * class, Note how it is used in paint( ). It's often referred to as the 'graphics context' */ // <applet code=AppletRun.class width =320 height =200></applet> import java.awt.*;
public class AppletRun extends Applet{
public void init( ){
public void paint(Graphics g){
|
For Applet Development
1) Put the applet tag into the source
file
2) Comment it out
// this leaves the tag visible as script but not as code
3) Save and compile as usual (using the .java extension and
javac)
4) Run appletviewer on source file as in appletviewer applet_file_name.java
To Set to HTML
1) Move your applet
tag into an appropriate location on a
HTML page
2) Save and compile your applet code as usual
(using the .java extension and javac)
3) Run appletviewer on the html file as in appletviewer html_file_name.html
4) Or, find the file and view in your browser
What version of JDK to use for
applets
At this point swing is not supported in the common browsers. Last testing is on Netscape 4.76 and Explorer 5. There is light at the end of the tunnel! The new Netscape beta 6 ran a swing applet. So perhaps it's just a matter of time. There is a lag time between the issue of the latest JDKs and browser support. Also Microsoft is not supporting Java past 1.1.x for proprietary reasons. Sun has responded by providing a JDK plug-in so the latest java versions can be supported in any browser. If you need widespread support for your applet now, (still true as of Nov 2000), you will have to stick to awt and Applet vs swing and JApplet or be sure the latest java plug-in is installed for your target browsers. Now too, you can use Netscape 6.x. . |
A Little on Jars
Jar files, for Java Archive Files,
are java's version of ZIP files, the
algorithm for archiving
developed and donated to the public domain by Phil Katz. Since JDK
1.1.x Java Jar Files
are synonomous with ZIP files with the compression turned on.You can
use a utility like
WinZip to create zip file (with
compression on) then rename the file with a .jar ending. You
can also make jar files from the command line using the jar command.
(The syntax is similar
to using the tar extraction utility in Unix.) You can get excruciating
detail from the Jar File
Specification in the JDK documentation( in docs
at jdk1.3/docs/guide/jar/jar.html). Plenty
of simple examples are available, for instance,
jar cf Globe.jar *.gif *.class
// places all .class and .gif files in the current directory into a JAR file named Globe.jar
Jars are a generally useful tool for such things as general
archiving, providing security
(in the process of signing an
applet) and are used in packaging JavaBeans.
In applets
they help organize the files that go into an applet but most importantly
they decrease the
download time of a web page over
the net allowing all the applet files to be downloaded in a
single jar archive.
// Van der Linden states there
is extra steps you have to go through to extract media files from a jar
file.
// He addresses this issue in
on pages 338 and 339 of 'Just Java'