Applets
Peter
Komisar
©
Conestoga
College latest
version
5.7 / 2010
Technologies
like Macromedia's Flash have won the
battle for certain niches that Java applets once might
have played a significant role, such as for visual display
ads and animations.
Java
applets,
though,
remain a very powerful technology,
able to download to the client's machine an application
that supplies the full power of the Java programming
language.
Today's
compilers
and
runtime
environments,
coupled
with fast PCs have
eliminated the lack of performance
that 'dogged' the earliest years of Applet use.
Lately,
new
tags
have
been provided for use in HTML
pages that pop up invitations to download the latest
Java Plug-Ins if Java is not supported by the user's
browser.
A
reference
section
on the Java Plug-In is appended at
the end of the
note.
Characterizing the Applet
Standalone
Applications vs. Container Managed Objects
To this point our
discussions have been focused on
running stand-alone Java
programs from the command
line. These are characterized by the
presence of a main( )
method and the use of command, ' java ' which invokes
the java interpreter. Stand-alone applications supply an
'in house'
Java Virtual Machine locally on the same
computer on which the application is run.
//
applets run in a 'context', supplied by a
web
browser
Java Program Variations
There are a variety Java
programs that can run within
a Java context provided by another
program. Servlets
for instance, run in a JVM supplied by a
web server.
The runtime environment in this case is referred to as
a 'Servlet
Engine'. ( Java Server Pages are a variation
of the servlet and use the same context.) Enterprise
JavaBeans also run in the context of
another program
that has been generically named, a 'Container'.
Applets are a third
example of this style of Java program.
They run in an JVM supplied by the browser. The Applet
API refers to this shell as the 'AppletContext'. The Applet
style of programming was developed early in Java's history,
being debuted on Sun workstation at Sun
One in 1995. A
more recent version of this style of programming is
the
'Midlet' that runs in very small devices such as cell
phones.
Java Objects That Run in the Context of a
Container JVM
Programming
Object
|
Supplied
JVM
|
Servlets
&
Java
Server
Pages |
Servlet
Engine |
EJBs
or
Enterprise
JavaBeans |
Container |
Applets
|
Browser
Context |
Midlets |
Mobile
Device
JVM
or
KVM* |
// KVM a Reduced Java Virtual Machine & Library
designed
// to run in the constrained environment of cell phones
Because Applets are run in
a Java Virtual Machine supplied
by a browser, it
follows that applets will use a different form
of programming than a standalone
Java application. These
differences are relatively minor and mainly involve not needing
to use the main( ) method.
Applets are able to
take
full advantage of all the capabilities you
have learned to use in
standalone applications and as such can
provide a very powerful way
distributing applications to multiple
clients via the browser.
A further benefit of
learning to use applets, is they introduce
the developer to the general approach which is taken by all
the container managed components and their APIs.
Applet Sandbox
Because powerful
code is being downloaded to a host machine
there is an opportunity for sinister code to do a lot of damage
on the host machine. To prevent this, applets by default are
contained in a security domain called the 'sandbox'. The
sandbox is like a
firewall that is built within a system around
an
application.
Restrictions are
based on what the inner
application can do
to the surrounding environment, for
instance, by default, applets
cannot access the local file system of the host machine that it
is downloaded to.
Following is a list
of functions that are not available to
downloaded applets.
Default Access of an Applet Downloaded Over
the Net
Signed applets
(signed as in digitally signed using encryption
keys) can be assigned privileges using Java's security system.
This supplies an alternative to the sandbox limitations on
standard applets where a trusted applet may be then assigned
special privileges such as the ability to read files from the local
machine.
Local
Applets are Privileged
The HTML
Connection
The applet is even more
unique in that it is a 'card carrying' member
of the HTML language in that it has it's own HTML tag. To use
applets
the programmer has to do some HTML coding in order to locate an
applet in a host web page that a browser may display. It is from
an
applet's tag in an HTML page that the browser is able to find and
run
the applet class file. The tag also supplies the browser with
the
dimensions the applet has been set to so the applet can be
sized
correctly in the page.
//
applets are referenced from special tags inside HTML documents
Applets Are AWT and Swing Visual
Components
Applets are full fledged
Java visual component. They need to be
painted on
the screen just like any other visual component. The
Applet class is
also a container component which means it can
be populated with
other visual components.
Applets
are
'HeavyWeight'
Containers
AWT's Applet class and
Swing's JApplet are both base container
classes. JApplet in Swing is one of the few
heavyweight or peer-
based components that can host other
lightweight Swing widgets.
//
Applets are heavyweight, container-type visual components.
Java's
Early
History
and
the Applet
In Java's early years,
applets were often used to create
visual
novelties on web pages.
Many of the first Java
textbooks were written with Java applets
serving as the base component over which Java's abilities were
demonstrated. These particular early books often emphasized
the use of Graphics and animations.
There is a large legacy of
Java applets that are still being run
on the net. If an applet needs the additional power of the Java
programming language it is still a popular choice for creating a
portable web 'codelet' that can run in a client's browser.
Applets in HTML & the Object Tag
It is necessary
to become familiar with the HTML page from
which an applet is
referenced by the browser. This page is
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 an HTML
page using the APPLET tag.
HTML
tags are not
case sensitive.
The
following example uses the convention where HTML
tags are set to upper case. The
APPLET tag must appear
somewhere within the BODY
tags of an HTML document.
//
hTmL
is
not
case sensitive, APPLET tags go in the
// BODY of the page.
Applet vs Object Tag
The HTML 4 specification
deprecates the APPLET tag
in favor of the OBJECT tag. The OBJECT tag is really
not any harder to use than the APPLET tag and for the
most part is simply a matter of substituting one for the
other. The Applet tag
attributes become a subset of the
larger and more generic attribute
list supported by the
OBJECT tag.
Because of the legacy of
applets on the web, the APPLET
will be supported for a very long
time to come and probably
indefinitely. Already there are trends that seek to support
legacy aspects of the Internet. The applet tag will live
probably as
long as we are using HTML in browsers.
Following is an
example of a basic Java APPLET tag
followed
by an Object tag that may be used to replace it.
You'll notice
there is an extra attribute called 'codetype'
in the Object tag. The
Object tag is designed to be a
generic container for a variety of
code types of which
Java applets are just
one. Also notice the 'code' attribute
is replaced with the 'classid' attribute.
Comparing APPLET and OBJECT Tags
<APPLET
code="Bubbles.class" width="500" height="500">
Bubbles!
</APPLET>
// This example may be rewritten with OBJECT as follows:
<OBJECT
codetype="application/java" classid="java:Bubbles.class"
width="500" height="500">
Bubbles!
</OBJECT>
Object Tag Attribute Tags not defined in Applet OBJECT tag
supercedes the applet tag in creating tags useful for any type
of object that can be referenced from an HTML
page. OBJECT uses
the 'id
' and 'class' attributes as document-wide identifiers. OBJECT tag
can also use the 'title' attribute to give an element a title. The
'style'
attribute is useful
for separating style from content. |
HTML
Tags of a Typical Page
The following HTML code
is the skeleton of a simple HTML
page. First the page is identified
as an HTML document by the
<HTML> tag. The <HEAD> tag
contains special information
about the page. For example the HEAD
can be used to supply
tips for search engines to find the page.
The <TITLE> tag is
used to name the document. This name
appears in the browsers
button for the page but not in the document.
The BODY is where
all the page content goes in a traditional HTML
page. The
APPLET tag should go in the BODY. In the following example
the Applet class resides in the same directory as the Web page.
Key HTML Tags
Basic Form of an HTML Page With Applet
<
HTML
>
<
HEAD >
<
TITLE ><!- appears in pages title bar
--> </
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 >
<!- the Applet
class file in this example would be
in the same
directory as the Web page. -->
Here
is an example that shows of a very minimal page
you can construct to use
to develop and test your applets.
Note the BODY and TITLE tag have been left out all
together.
Minimal HTML Page With Applet
<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.
The Applet Tag in Detail
Following is a more
detailed
description of the APPLET tag
with all it's attributes listed.
Notice most of these attributes are
located within the angle braces of the opening APPLET tag.
Only the PARAM tags are located between
the two Applet
Tags. We carry forward a brief comparison of Applet
and
Object tags in comments below each tag or in the regular text.
<APPLET
CODE
= class file (file or URL)
HEIGHT = pixels
WIDTH = pixels
<!-- [ ]
square brackets indicate optional
tags -->
[ CODEBASE = URL directory ]
[ ALT =
alternate text message ]
[
ARCHIVE = names of JAR files ]
[ ALIGN = alignment ]
[ NAME = name for other applets on page ]
[ HSPACE =
pixel ]
[
VSPACE = pixel ]
> <!-- note above instructions are enclosed withing the first applet tag -->
[
< PARAM NAME = identifier VALUE = value > ]
[ < PARAM NAME
= identifier VALUE = value > ]
. . . . . . . . ..
[alternate HTML ]
</
APPLET >
<!-- CODE WIDTH and HEIGHT tags are mandatory
-->
WIDTH & HEIGHT Attributes
The
width and height tags are obligatory tags. HTML requires
that they be
included in the applet tag. They specify
the width
and height of the applet in pixels These sizes reflect
the
dimensions the applet will attempt to attain. Other page items
may
constrain the size of the applet is actually allowed to be.
The getSize( ) method
Applet
inherits from Component
class can be used to report the actual
size the browser
has given to the applet. This method
returns a
Dimension
object from which the height and width can be
referenced.
The following code sample
shows an overridden
paint( )
method extracted from a sample applet. We explain the
details of this method later.
//
Width and height attributes are the same in both
// Applet & Object
Tags
Example
public void
paint( Graphics g){
Dimension d=getSize( );
g.setFont(new Font("Monospaced",
Font.BOLD,16));
g.drawString
("getSize reports width and height "
+ d.width +" "+ d.height, 50, 60 );
}
The CODE Attribute
The applet class that
will run in an HTML page when
that page is visited is specified by
the CODE attribute.
The code attribute
should be
specified in quotes despite
the fact that browsers may
forgive their omission.
( HTML veterans say
that leaving quotes out might effect
the
operation of older browsers. Also new XML and
XHTML standards require attribute values be specified
inside double quotes so it is a good general practice. )
Notice it is the class file that is specified to the code attribute.
Example
code="X.class"
In HTML
specifications, the CODE attribute is described
as specifiable by a path
relative to the
calling HTML or
URL.
More than one text have been printed stating this.
In
practice, with many of today's
browsers this isn't the case.
(Try
for yourself! It should be tested periodically in any case. )
Van der Linden in his book 'Just Java'
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 Object tag uses the combination of codetype and classid
//
ie. codetype="application/java"
classid="java:Bubbles.class"
The CODEBASE Attribute
The 'codebase' attribute
is very
important, especially in
light of the way the 'code' tag is currently
implemented.
The 'codebase' attribute can
be used to
specify
(The
relative path is relative to where
the calling HTML
file is located.)
The 'codebase' attribute may undergo semantic changes
which are described in
the W3 HTML 4 specification. The
'codebase'
attribute will be restricted to sub-directories of
the
directory containing the current document for security
reasons.
Note this restriction doesn't exist
at this time as
will be evident when you look at the following
example.
//
memo: retest
Examples Using the CODEBASE Attribute
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 for Codebase Examples
P
_|_
| |
H C
| |
H2
C2
Example
1
//
accessing by an absolute path
<applet code="T.class"
codebase="C:/P/C/C2" width="300"
height="300">
</applet>
Example
2
//
accessing by a path relative to the location of the calling HTML page
<applet code="T.class"
codebase="../../C/C2" width="300"
height="300">
</applet>
Example
3
//
accessing the applet using an absolute path via a File URL form on a
local machine
<applet code="T.class"
codebase="file:///c:/newcode/P/C/C2" width="300"
height="300">
</applet>
Example
4
// using an absolute path via an HTTP URL for an
applet
located on an Internet machine
<applet
code="T.class" codebase="http://www.sentex.net/C/A/T"
width="90" height="90">
</applet>
// If HTML 4 is fully
implemented in the browser you are using, accessing a
// directory as in example 2 may not be allowed.
The ALT Attribute
The ALT attribute
provides an
alternate text for browsers that
know the
tag but do not support applets. This tag is useful for
really old
browser, that don't support Java, and may be useful
for really new browsers that may leave
downloading the Java
plug-in up to the
user. It may now also be useful for new
lightweight browsers used on hand-held devices that eliminate
items from their displays.
The ALT tag is the same in
APPLET and OBJECT tags.
Example
< APPLET
CODE = "Arizona.class" WIDTH
="400" HEIGHT ="250"
ALT = "Picture of the Grand Canyon" >
< /APPLET >
HSPACE, VSPACE & ALIGN Attributes
These variables 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 controls the distance in
pixels between the applet's
top and bottom boundaries and any
adjacent HTML elements.
ALIGN values may
be assigned any
of the following HTML
constants,
These tags are the same in both Object and Applet tags.
Example
ALIGN="MIDDLE"
The ARCHIVE Attribute
A
JAR or Java 'ARchive' file is a
'zipped' collection of files.
The ARCHIVE tag identifies JAR
files on the server that the
browser needs to download. Using JAR files
speeds
remote
class loading. Bundling files in JARs reduces what might
be
several download transactions to a single archive download.
The
CODE tag still needed to
identify the class inside the jar
that needs to be executed. The Object tag uses the ARCHIVE
attribute in the
same way as does the Applet tag.
Example
<APPLET
CODE=X.class WIDTH=90 HEIGHT=60
ARCHIVE="Zip_In.jar" >
< /APPLET >
Multiple
JARs can be downloaded using a comma-separated
list as is shown in the next
example.
Example
<APPLET
CODE=A.class
WIDTH=100 HEIGHT=100 ARCHIVE="A.jar,
B.jar, C.jar">
< /APPLET
>
The NAME & VALUE Attributes
The NAME tag is used in the PARAM tag shown below.<applet code=clock.class name=clock1>// http://docstore.mik.ua/orelly/web/html/ch13_01.html
</applet>
<applet code=clock.class name=clock2>
</applet>
<applet code=setter.class>
<param name=clockToSet value=clock1>
</applet>
<applet code=setter.class>
<param name=clockToSet value=clock2>
</applet>
The
PARAM
Tag
// used to pass values to applet
via HTML
PARAM tags are the only
nested elements defined for the
APPLET tag. Unlike
the other APPLET attributes, PARAM
appears between the two applet tags. The PARAM tag
allows the
HTML developer to supply parameters to a
Java
applet without having to rework
the Java code itself.
Whether a multimedia
player, a weather applet or a news
reel, the HTML
developer can pass information to the applet
via the PARAM Tags
without having to recompile the applet.
The PARAM tag has two
attributes, NAME and VALUE
which can be used to supply name value
pairs to the applet.
Example
// lower case html for a change
<applet
code="ParTake.class" width =300 height=300>
<param name="artisto" value="Pablo Picasso">
<param name=title value="Bather With Beach Ball">
<param name=image value="Bather.jpg">
<param name=imageNo value="32">
</applet>
The Applet Class
Applet & JApplet
When
we talk about applets, we must consider both the
classic Applet class
found in the java.awt
package and
the newer JApplet which resides in the javax.swing
package.
Applet JApplet
Differences
Applet
and
JApplet
are
different in a couple of ways.
Applet class has a flow layout manager by default
while
the JApplet class has a border layout as the default
layout
manager. Recall the flow layout
allows components
to remain their preferred size and adds
them left to right,
top to bottom,
centering as addition are made.
The
border layout on
the other hand has five fixed regions,
east, west south, north and
center and has a hybrid policy
where
components are allowed to be their preferred size
on one axis
but are controlled by the layout on the
other
axis. Only one component can occupy each
of the five
regions of the border layout at a time.
// JApplet's default layout is BorderLayout, Applet's is FlowLayout
JApplet
also
has
the
more complex layered behavior
that has been incorporated into JFrame,
where an area
to add a menu is provided and layered panes are used
to show pop up menus and
tooltips. JApplet like other
Swing
components can have icons added.
Classic
Applets
Were
the Safest
Bet For Widespread Support
// no
longer so
relevant with the
Java Plug-in and high speed connections
In the past browsers did
not provide uniform support for newer
versions of Java. Microsoft browsers for a long time supported
a dated version of Java (JDK1.7). ) Accordingly,
classic Applet
enjoyed widespread support and were a 'safe bet'. .
Today
there
is
considerable support in browsers for downloading
the Java Plug-In, similar to how you might be invited to download
Macromedia's Flash plug-in if it isn't on your PC.
With
the prevalence of high speed connections, the complication
to get a recent version of Java with Swing support is no longer as
much an issue as it was in the past. This makes using the newer
Swing JApplet much more viable.
The
Sun Microsoft Truce Helped Bring Support the Swing Applets
Recently
Sun
and
Microsoft buried the hatchet, a shed a long
running competitive feud. Perhaps old adversaries were allying
perceiving Linux and generally the Open Source paradigm as a
threat to the proprietary model.
Now
in 2010, Oracle has bought Sun and Google is the new
gorilla on the block and Oracle finds itself supporting Sun's
position of resisting splintering of the Java language into
incompatible dialects. .
All
things considered, the scales seemed to have tipped in favor
of support for Swing applets, so classic AWT applets can be put
to pasture.
A
word of caution, when developing applets, sometimes browsers
can be 'too effective' at
caching an
applet
and won't load a revised
version instead reverting to the cached
version. If you are making
changes to an applet's code, and they
are not being reflected in
the browser it is
reasonable to suspect you are seeing an earlier
cached
version.
Though,
refresh
or
reload
should
get rid of the applet, sometimes
it is necessary
to reopen the browser on the applet
containing page.
If this doesn't work you can close and
reopen the browser itself!
Clearing Cache
Clearing
the
cache
is
the best strategy.
On
Mozilla go to:
Edit
--> Preferences --> Advanced --> Cache --> Clear Cache
On
Window's Explorer go to:
Tools
-->
Internet
Options
--> Delete Files
//
get rid of cached pages by
1) Refreshing 2) Reopening on File 3)
Clearing Cache // 4 ) Restart browser
You may still find you
have to close a browser and reopen it
occasionally.
Methods of the Applet Life Cycle
When
an applet is run in a browser a series of methods are
called which
represent the applet's life cycle.
The Java
developer overrides these methods in order to derive the
desired behavior. Following
are the methods that are called
during normal applet service that
can be overridden to control
the
functionality of the applet.
Table
Summarizing the Applet's Life Cycle Methods
//
info from JDK Documentation
public void |
Called
by the browser or appletviewer
when |
// acts like a constructor |
public void |
After init( ) the
browser calls
start( ). The |
// functions like the main method |
public
void |
Called whenever the
component needs to be |
// standard component graphics call |
public void |
Called when the browser
leaves the
applet's page |
// stops applet but still in cache |
public void
|
Called
to
inform
this
applet
that it is being reclaimed and that it should destroy any resources that it has allocated. |
//
does
resource cleanup, release threads here |
init(
) // initialize and load GUIs in init( )
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 acts like a constructor in a regular
Java
program to initialize values. GUI components will typically be
instantiated and added
to the applet from inside the init( ) method.
start( ) // like main( )
The
start( ) method is called after init( ). This method is like the main( )
method in a
stand-alone application. It is different in that what triggers
it is
the page being visited in the
browser. If the applet is going to spawn
threads when the applet
is visited start( ) is where these threads
are
activated.
paint(Graphics g )
After
start(
),
the
paint( ) method is called. The paint method is not
unique to applets. This is the same
method that is used by all of
Java's visual
components. As with other components
paint( ) can
be overridden to create custom
displays or to create custom
components. The paint( ) method supplies a handle to a
graphics
context object that can be used to
access the drawing methods
of the classic
Graphics class as well as the methods of the new
2D graphics class.
The paint( ) method is automatically
called
whenever a component needs painting.
stop( )
When
the browser leaves the page, stop( ) is called. Stop shuts
down the
applet and closes any resources that
may have been
associated with it. After the stop( ) method
is
called
the applet
is down but not out! The applet still resides in
memory cache in
case the user
returns to the applet's page.
destroy( )
The
destroy(
)
method
is the final method of the applet life cycle. It
is
called to tell the applet that it is being reclaimed and thus
should
release any
resources that it has allocated. The stop( ) method
is
always called before destroy( ). The destroy( )
,method supplies a
good place to
kill any threads
that were created in init( ) and started
in start( ). Applet's default version
of
destroy( ) does not do anything.
Other Applet Methods
Following
is
a
table
summary of key Applet's methods. They
are supplied here mainly for reference and to show what sorts
of things are available for use.
Aside from Applet's
life cycle methods, there are methods for
getting and playing
audio files. The
applet class also has several
methods for handling images. Notice the methods provided for
obtaining parameters from the HTML page
that the applet resides
in.
Applet class
also has informational methods that tell which
directory the applet is
located in and which
directory the
HTML page that references the
applet is located in. Applet
class has a method that returns a handle to the Java
Runtime
Environment in which
the applet is running. The method,
getAppletContext( ) returns an
object of the
AppletContext
class. AppletContext supplies methods to control the
HTML
environment
in
which
the
applet is resident.
Survey of Applet
Methods
destroy( ) |
Called
by
the
browser
to tell this applet |
AppletContext
|
Determines
this
applet's
context,
|
String getAppletInfo( ) |
Returns information about this applet. |
AudioClip |
Returns
the
AudioClip
object
specified |
AudioClip
getAudioClip |
Returns
the
AudioClip
object
specified |
URL getCodeBase( ) |
Gets the base URL. |
URL getDocumentBase( ) |
Gets the document URL. |
Image getImage(URL url) |
Returns
an
Image
object
that can |
Image
getImage |
Returns
an
Image
object
that can then |
Locale getLocale( ) |
Gets
the Locale for the applet, if it |
String
getParameter |
Returns
the
value
of
the named |
String[][] |
Returns
info
about
parameters
that are |
void init( ) |
Called
by
the
browser
or applet viewer |
boolean isActive( ) |
Determines if this applet is active. |
static
AudioClip |
Get an audio clip from the given URL |
void play(URL url) |
Plays
the audio clip at the specified |
void
play |
Plays
the audio clip given the URL |
void
resize |
Requests that this applet be resized. |
void
resize |
Requests that this applet be resized. |
void
setStub |
Sets this applet's stub. |
void
showStatus |
Requests
this
argument
string
be |
void start() |
Called
by
the
browser
or applet- |
void stop() |
Called
by
the
browser
or applet- |
'HelloWorld' in an Applet
AWT Applet Imports
If an applet is
built using the classic AWT package the
applet
package must be imported along with the java.awt package.
Example
import java.awt.*;
import java.applet.*;
Applet is Public
The second key aspect to
creating applets is simply to extend
the Applet class. The compiler will tell you that the
public keyword
must be included in the class signature. An applet not marked
public will compile with default
access however will fail at runtime.
An IllegalAccessException
is
thrown, because a subclass
has been defined that is more private
than it's parent class.
Example
public ThisApplet extends Applet { /*etc. */ }
Override Life Cycle Methods
Finally, in order
for your applet to do anything, one of the
applet's life cycle
methods must be overridden. In most
HelloWorld examples
written for applets, the paint( ) method
is overridden and a
Graphic's class method, drawString( ) is
used to draw the text
HelloWorld over the component. Just
to make the code more
interesting looking, we borrow another
method from the Graphics
class to make the font bold.
Hello World in an Applet Code Sample
// <applet code="OK.class" width ="600" height="300"></applet>Adding the Applet Tag to Source Code
For convenience, the Java environment comes with a command
line tool called appletviewer
that allows applets to be viewed
before they are set inside HTML pages.
Adding the APPLET tag to
the top of the source code
there is
enough information for 'appletviewer' to run the source
code as
the document containing the applet.
The source code still
needs to be compiled to a class file as the
tag only provides a
reference to the class file.
Because appletviewer first
looks for
the applet tag, it is the Java
source code is supplied as an argument to
the 'appletviewer' tool.
The example above as well
as the following examples shows the
minimum Applet tag added to the source code.
Note the tag is
commented out. This makes it a comment to the Java
code but
in terms of HTML the comment symbols are just document
character
content and as an HTML reader, 'appletviewer' only 'sees'
the code
tagged inside angle brackets. Such a tag is exampled below.
Example
// <applet code=OK.class width =400 height =100></applet>
// Applet
Tag Commented out & Added to Java Applet Source Code
The following
example shows that the Java Source code
is supplied
as an argument
to the appletviewer command,
which views the source code first as an
HTML document.
Example
C:\> appletviewer OK.java
//
appletviewer finds the applet reference then runs the class after
finding it
Summary For Using appletviewer Top Develop Applets
Following
is
a
summary
of the steps involved in developing applets.
First the
APPLET tag is put into the source code and
commented
out. The applet is saved and
compiled like any other Java file. Then,
'appletviewer' is run not on the class name
but
using
the Java source
file containing
the applet tag as an argument.
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.
Example
> appletviewer applet_file_name.java
Setting the Applet to the HTML Page
Once
the applet is running like you want it to it can be moved
into an
HTML file. Initially,
even
the
HTML file can be tested with
appletviewer. The final test is to open the
page
in whichever
browsers you want the page
and applet to work
in.
1)
Move your applet tag into the body of an HTML page
2)
Assuming the Java source code has been
compiled,
run appletviewer on the HTML
file.
Example
> appletviewer html_file_name.html
3) The page is also ready
to view in any Java-enabled
browser.
'HelloWorld' in Swing
Swing Imports
Following is the Swing
version of 'HelloWorld' using
Swing
components. First the imports are different.
Example
import java.awt.*;
import javax.swing.*;
The second difference is
the JApplet class is extended.
Notice too that now any components
added to JApplet
will be added to a border layout and will need
to call
getContentPane( ).
While In earlier years
Swing applets would not run in
Netscape
4.x or Internet Explorer 5.x
browsers, the newer Java plug-in
has made Swing support nearly universal on the web.
Following is the Swing
version of
'HelloWorld'. This example
includes the
commented out applet tag.
Hello World using the Swing Class, JApplet
//
<applet code=OK2.class width =400 height =100></applet>
import java.awt.*;
import javax.swing.*;
public class OK2 extends
JApplet{
public void paint( Graphics g){
g.setFont(new Font("Monospaced", Font.BOLD, 22));
g.drawString("OK, It's Hello World In Swing", 50, 60 );
}
}
Overriding Applets Methods & Building GUIs in Applets
The
following code example shows the approach one can take
to build a GUI
in an applet. Basically, if the components
need
to be accessed from other class members
the components will
need to be declared in class scope. The
instantiation will usually
be done
in the init( ) method.
In
this example all the
applet life cycle methods are overridden.
The console output and the visual components
are
used to signal
the effects of each overridden
method.
To
see paint being called
resize the window dramatically by
dragging and dropping the
applet frame with the mouse. The
stop( )
method will be called when the applet is
iconified or
closed. Try iconifying a few times first before closing
out the
applet. Following is
the code.
Applet
GUI and Overriding Example
//
<applet code=Cyclet.class width=500 height=200></applet>
import java.net.*;
import java.awt.*;
import java.applet.*;
public class Cyclet extends Applet{
TextField init,start,paint,stop;
public void init( ){
System.out.println("Init has been called");
setLayout(new GridLayout(5,1));
init = new TextField("Init is called");
start= new TextField();
paint= new TextField();
stop = new TextField();
add(new Label("Use menu, (upper right).
Resize to see paint() called. Restart to see stop() called"));
add(init);
add(start);
add(paint);
add(stop);
}
public void start( ){
System.out.println("Start has been
called");
start.setText("Start has been
called");
}
public void stop( ){
System.out.println("Stop has been
called");
stop.setText("Stop is called");
}
public void paint( Graphics g){
paint.setText("Paint is called");
System.out.println("Paint has been called");
}
public void destroy( ){
paint.setText("Destroy is called");
System.out.println("Destroy has been called");
}
}
Self Test Self Test With Answers
1) Which of the
following does not run in the context of another program
a) stand-alone
applications
b) an applet
c) a servlet
d) an enterprise
java bean
2) Which of the following is not a mandatory applet tag?
a ) code
b) width
c) height
d) codebase
3) Mark the method that is not one of the standard methods overridden in an applet.
a) init( )
b) start(
)
c) run( )
d) stop( )
e) paint( )
4) Which of the following lines is not correct in the following applet?
a) import
java.awt.*;
b) import java.awt.applet.*;
c) public
ThisApplet extends Applet {
d) public void paint( Graphics g){
g.drawString("Hi!", 10, 10 ); }
}
5) Appletviewer
a) is a utility to
facilitate quick viewing of applets during development
b)
requires as an argument a class file just as is passed to the 'java'
command
c) can run an HTML file or
a Java source file
d) to run an applet
from source file the applet tag must be supplied and
commented out.
6) True or False:
Because the init( ) method of an applet acts like a
constructor,
constructors cannot be used with applets.
7) In which of the
following methods of the applet life cycle is the recommended
location for building GUIs.
a) init( )
b) start( )
c)
paint( )
d) stop( )
8) Which of the
following statements is not correct. While accessing
parameters
from the applet tag
a)
The PARAM tag has a NAME and and a VALUE
component
b) an
applets getParameter( ) method argument must match case sensitive
with
the value assigned to the NAME attribute in the PARAM tag.
c)
The PARAM tag is located between the two applet tags
d)
The PARAM tag does not need a closing </ PARAM> tag
Exercise
1) In this exercise 4
AWT applets are created that will be used
in combination to print
a statement to screen. Use Label objects
added to the overridden
init( ) method in two of the applets to
add text. In the other
two use the Graphics method, drawString( )
as exampled in the
notes above.
Begin by using
appletviewer together with a commented out applet
tag, to make sure
each applet works.
Transfer the four applet
code tags to an HTML page. You may use
ALIGN, HSPACE and VSPACE to locate
the 4 applets on the page.
One approach successfully
used is to use a break tag, <BR> or
a paragraph tag, <P>, to pair applets on different rows.
If you are savvy at the
use of HTML you might use spans or other
tags to do the job.
Use each applets height
and width
attributes so the four applets fill
the page. Include an ALT tag in
applet tag so an alternative message
is provided in case the page
is opened into a browser that doesn't
support Java. Once the
applet and page are prepared, open the
page in Explorer and
Netscape.
2) Convert the AWT
applets to Swing JApplets. Remember, JApplet
uses a
BorderLayout, though if we are adding a single label
to each
applet this shouldn't matter. Also you need to import the
javax.swing
package.
3) Create a second HTML
page to support these
applets. Instead of
transferring the Applet tags, convert them to
the W3C recommended
Object tag. Observe in Netscape ( Mozilla )
and Explorer. Briefly report
what happened what results you obtained, using the different browsers.
Optional
There are some fancy Universal IDs that
can be used
to make the Object
tag work correctly in Explorer.
4 ) Find on the web the
formulation of the Object tag that has ID
and
attributes allowing the Object Tag to work in Internet Explorer.
// so far we have found support
in Mozilla but not in Explorer for the minimum forms
// of the object tag. If you seek out examples there are extra
attributes you can add
// to get Object tag to work Explorer. Above, in Q.3 I am only asking
to test the simple
// version of Object and report observations in two browsers.