|
|||||
Web
Design & Development CS506
VU
Lesson
20
Applets
A
small program written in
Java and included in a HTML
page.
It is
independent of the operating system on
which it runs
An
applet is a Panel that allows
interaction with a Java
program
A
applet is typically embedded in a Web
page and can be run from a
browser
You
need special HTML in the Web page to tell
the browser about the applet
For
security reasons, applets run in a
sandbox: they have no access to the
client's file system
Applets
Support
Most
modern browsers support Java 1.4 if
they have the appropriate
plugin
Sun
provides an application appletviewerto
view applets without using
browser.
In general
you should try to write
applets that can be run with
any browser
What an
Applet is?
You
write an applet by extending the
class Appletor
JApplet
Applet
is just a class like any
other; you can even use it
in applications if you
want
When
you write an applet, you
are only writing part of a
program
The
browser supplies the main method
The
genealogy of Applet
The
following figure shows the
inheritance hierarchy of the JApplet
class. This hierarchy determines
much
of
what an applet can do and
how, as you'll see on the
next few pages.
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container|+----java.awt.Panel
|
+----java.applet.Applet|+----javax.swing.JApplet
Example
Code 20.1: Writing a Simple
Applet
Below
is the source code for an
applet called HelloApplet.
This displays a "Hello
World" string. Note
that
no
main method has been
provided.
//
File HelloApplet.java
//step 1:
importing required packagesimport
java.awt.*;import
javax.swing.*;
//
extending class from JApplet
so that our class also
becomes an//appletpublic class
HelloApplet extends
JApplet
{
//
overriding paint method
public
void paint(Graphics g) {
//
write code here u want to
display & draw by using// Graphics
objectg.drawString("Hello
World",
30 , 30);
} } //
end class
After
defining the HelloApplet.java, the next
step is to write .html file.
Below is the source code
of
Test.html
file. The Test.html contains the
ordinary html code except
one.
<html>
<head>
<title>
Simple Applet
</title>
</head>
149
Web
Design & Development CS506
VU
<body>
<!--
providing the class name of
applet with
width
&height--!>
<applet
code="HelloApplet.class"
width=150
height=100>
</applet>
</body>
</html>
Compile
& Execute
By
simply double clicking on
Test.html file, you can
view the applet in your browser.
However, you can
also
use the appletviewer java
program for executing or
running applets.
The
applet viewer is invoked
from the command line by the
command
appletviewer
htmlfile
where
htmlfile is the name of the file
that contains the html document. For
our example, the
command
looks
like this:
appletviewer
Test.html
As a
result, you will see the
following output
Applet
Life Cycle Methods
When
an applet is loaded, an instance of the
applet's controlling class (an Applet
subclass) is created.
After
that
an applet passes through
some stages or methods, each
of them are build for
specific purpose
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
The
applet's life cycle methods
are called in the specific
order shown below. Not every
applet needs to
override
every one of these
methods.
150
Web
Design & Development CS506
VU
Let's
take a look on each method in
detail and find out what
they do
init(
)
Is
called only once.
The
purpose of init( ) is to initialize the
applet each time it's
loaded (or reloaded).
You
can think of it as a constructor
start(
)
To
start the applet's execution
For
example, when the applet's loaded or
when the user revisits a
page that contains the
applet
start( ) is
also called whenever the browser is
maximized
paint(
)
paint(
) is called for the first
time when the applet becomes
visible
Whenever
applet needs to be repainted,
paint( ) is called
again
Do
all your painting in paint(
), or in a method that is called from
paint( )
stop(
)
To
stop the applet's execution, such as
when the user leaves the applet's
page or quits the browser.
stop( ) is
also called whenever the browser is
minimized
destroy(
)
Is
called only once.
To
perform a final
cleanup in
preparation for
unloading
Example
Code 20.2: Understanding Applet
Life Cycle
Methods
The
following code example helps
you in understanding the calling
sequence of applet's life
cycle
methods.
These methods are only
displaying debugging statements on the
console.
//
File AppletDemo.java
//step 1:
importing required packagesimport
java.awt.*;import
javax.swing.*;
//
extending class from JApplet
so that our class also
becomes an//appletpublic
class
AppletDemo extends JApplet {
//
overriding init method
151
Web
Design & Development CS506
VU
public
void init ( ) {
System.out.println("init()
called");
}
//
overriding start method
public
void start ( ){
System.out.println("start()
called");
}
//
overriding paint method
public
void paint(Graphics
g){
System.out.println("paint()
called");
}
//
overriding stop method
public
void stop(){
System.out.println("stop()
called");
}
//
overriding destroy method
public
void destroy(){
System.out.println("destroy()
called");
}
} //
end class
The
DemoTest.html file is using
this applet. The code
snippet of it given
below:
<html>
<head> <title> Applet Life
Cycle Methods
</title></head>
<body>
<!--
providing the class name of
applet with width
&height--!>
<applet
code="AppletDemo.class"
width=150
height=100>
</applet></body></html>
Compile
& Execute
To understand the
calling sequence of applet
life cycle methods, you have
to execute it by using
appletviewer
command. Do experiments like maximizing,
minimizing the applet, bringing another
window
in
front of applet and keep an eye on
console output.
Example
Code 20.3: Animated Java
Word Sample Output
The
browser output of the program is given
below:
Design
Process
The
Program in a single call of paint
method
Draws
string "java" on 40 random
locations
For
every drawing, it selects random
font out of 4 different
fonts
152
Web
Design & Development CS506
VU
For
every drawing, it selects random
color out of 256 * 256 *
256 RGB colors
Repaint
is called after every 1000
ms.
After
10 calls to repaint, screen is
cleared
Generating
Random Numbers
Use
static method random of Math
class
Math.random()
;
Returns
positive double value greater
than or equal to 0.0 or less
than 1.0.
Multiply
the number with appropriate scaling
factor to increase the range and type
cast it, if
needed.
int i
= (int)( Math.random() * 5 );//
will generate random numbers
between 0 & 4.
Program's
Modules
The
program is build using many
custom methods. Let's
discuss each of them one by one that
will help in
understanding
the overall logic of the
program.
. drawJava(
)
As
name indicates, this method will be
used to write String "java"
on random locations. The code
is
given
below:
// method
drawJava
public
void drawJava(Graphics2D g2)
{
//
generate first number randomly.
The panel width is 1000int x
= (int) (Math.random() * 1000);
//
generate
second number randomly. The
panel height is 700
int y
= (int) (Math.random() * 700); //
draw String on these
randomly
selected
numebrsg2.drawString("java", x, y);
}
. chooseColor(
)
This
method will choose color
randomly out of 256 * 256 *
256 possible colors. The code
snippet is given
below:
// method
chooseColor
public
Color chooseColor() {
// choosing red
color value randomly
int r
= (int) (Math.random() *
255);
// choosing
green color value
randomly
int g
= (int) (Math.random() *
255);
// choosing
blue color value
randomly
int b
= (int) (Math.random() *
255);
//
constructing a color by providing
R-G-B valuesColor c = new
Color(r, g, b);
//
returning color
return
c;
}
. chooseFont(
)
This
method will choose a Font
for text (java) to be
displayed out of 4 available
fonts. The code snippet
is
given
below:
// method
chooseFont
public
Font chooseFont() {
//
generating a random value that helps in
choosing a fontint fontChoice =
(int)
(Math.random()
* 4) + 1;
//
declaring font reference
Font
f = null;
//
using switch based logic
for selecting font
switch
(fontChoice) {
153
Web
Design & Development CS506
VU
case
1: f = new Font("Serif", Font.BOLD +
Font.ITALIC, 20);break;
case
2: f = new Font("SansSerif", Font.PLAIN,
17);break;
case
3: f = new Font("Monospaced",
Font.ITALIC, 23);break;
case
4: f = new Font("Dialog", Font.ITALIC,
30);break;
} // end
switch
// returns
Font object
return
f;
}
//end chooseFont
. paint(
)
The
last method to be discussed here is
paint( ). By overriding this method, we
will print string
"java"
on 40 random
locations. For every
drawing, it selects random font
out of 4 different fonts &
random
color
out of 256 * 256 * 256
RGB colors.
Let's
see, how it happens:
//
overriding method
paint
public
void paint(Graphics g) {
//
incrementing clear counter
variable.
clearCounter++;
//
printing 40 "java" strings on different
locations by// selcting random
font & colorfor (int i = 1;
i
<=
40; i++) {
// choosing random
color by calling chooseColor()
method
Color
c = chooseColor();
//
setting color
g2.setColor(c);
// choosing random
Font by calling chooseColor()
method
Font
f = chooseFont();
g2.setFont(f);
//
drawing string "java" by
calling drawJava() method
drawJava(g2);
} // end
for loop Graphics2D g2 =
(Graphics2D) g;
//
checking if paint is called 10 times
then clears the// screen and
set counter again to zero
if
(clearCounter
== 10) {
g2.clearRect(0, 0,
1000, 700);clearCounter = 0; } }
//
end
paint method
Merging
Pieces
By
inserting all method inside
JavaAnim.java class, the program
will look like one given
below. Notice that
it contains
methods discussed above with
some extra code with
which you are already
familiar.
//
File JavaAnim.java
//step 1:
importing required
packages
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public
class JavaAnim extends
JApplet implements ActionListener
{
//
used to count how many times
paint is called
int
clearCounter;
//
declaring Timer reference
Timer
t;
154
Web
Design & Development CS506
VU
//
overriding init method, used to
initialize variables
public
void init() {
setBackground(Color.black);
clearCounter
= 0;
Timer
t = new Timer(1000,
this);
t.start();
}
//
overriding paint method discussed
above
public
void paint(Graphics g) {
clearCounter++;
Graphics2D
g2 = (Graphics2D) g;
if
(clearCounter == 10) {
g2.clearRect(0, 0,
1000, 700);
clearCounter
= 0;
}
for
(int i = 1; i <= 40; i++)
{
Color
c = chooseColor();
g2.setColor(c);
Font
f = chooseFont();
g2.setFont(f);
drawJava(g2);
}
}
//
overriding actionPerformed()of
ActionListener interface// called by
Timer object
public
void actionPerformed(ActionEvent ae)
{
repaint();
}
// chooseColor
method discussed above
public
Color chooseColor() {
int r
= (int) (Math.random() *
255);
int g
= (int) (Math.random() *
255);
int b
= (int) (Math.random() *
255);
Color
c = new Color(r, g,
b);
return
c;
}
// chooseFont
method discussed
above
public
Font chooseFont() {
int
fontChoice = (int) (Math.random() * 4) +
1;
Font
f = null;
switch
(fontChoice) {
case
1: f = new Font("Serif", Font.BOLD +
Font.ITALIC, 20);break;
case
2: f = new Font("SansSerif", Font.PLAIN,
17);break;
case
3: f = new Font("Monospaced",
Font.ITALIC, 23);break;
case
4: f = new Font("Dialog", Font.ITALIC,
30);break;
}
return
f;
}
//
drawJava() method discussed
above
public
void drawJava(Graphics2D g2) {
int x
= (int) (Math.random() *
1000);
int y
= (int) (Math.random() *
700);
g2.drawString("java",
x, y);
155
Web
Design & Development CS506
VU
}
} //
end class
The
AnimTest.html file is using
this applet. The code
snippet of it given
below:
<html>
<head>
<title>
Animated Java Word
</title>
</head>
<body>
<applet
code="JavaAnim.class" width=1000 height=700>
</applet>
</body>
</html>
Compile
& Execute
You
can execute it directly
using browser or by using appletviewer
application. For having fun,
you can use
"your
name" instead of "java" and
watch it in different colors ☺
References:
. Java, A
Lab Course by Umair
Javed
. Writing
Applets
. http://java.sun.com/docs/books/tutorial/applet/
156
Table of Contents:
|
|||||