Unit III
Unit III
*
Chapter 14 Applets
***************************************************************************
****
14.1 Introduction
An Applet is a Java program that runs in a Web browser.
Applets are small Java programs that are primarily used for Internet computing. They
can be transported over the Internet from one computer to another and runs using the
Appletviewer or any Web Browser that supports Java.
An Applet, like any other application program, can do many things for us. It can perform
arithmetic operations, display graphics, play sounds, accept user input, create animation,
and play interactive games.
An Applet is embedded in an HTML page using the APPLET tag and hosted on
a web server.
Applets are used to make the web site more dynamic and entertaining.
Local and Remote Applets
An applet developed locally and stored in a local system is known as a local applet.
When a Web page is trying to find a local applet, it does not need to use the Internet, and
therefore the local system does not require the Internet connection. It simply searches the
directories in the local system and locates and loads the specified applet.
A remote applet is that which is developed by someone else and stored on a
computer connected to the Internet. If our system is connected to the Internet, we can
download the remote applet onto our system via the Internet and run it.
In order to locate and load a remote applet, we must know the applet’s address on the
Web. This address is known as Uniform Resource Locator (URL) and must be specified
in the applet’s HTML document as the value of the CODEBASE attribute.
Example:
CODEBASE=http://www.netserve.com/applets
In the case of local applets, CODEBASE may be absent or may specify a local directory.
14.2 Differences between Applets and Applications
Applet Application
Applets are small Java programs that are Applications are stand-alone programs that can be
designed to be included with the HTML executed independently without using the web
web document. They require a Java-enabled browser.
web browser for execution.
Applet does not require a main function for Application program requires a main function
its execution. for its execution.
Applets can't read from or write to the files An application can read from or write to the files
on the local computer. on the local computer.
An Applet requires Graphical User Interface An application doesn't require Graphical User
(GUI). Interface (GUI).
Applets can't communicate with other The application can communicate with other
servers on the network. servers on the network.
Applets can only access the browser Applications can access all kinds of resources
specific services. They don’t have access to available on the system.
the local system.
An applet program is needed to perform An application program is needed to perform
small tasks or the part of it. some task directly for the user.
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a
window that is 200 pixels wide and 60 pixels high.
An applet code will have a general format as shown below:
import java.awt.*;
import java.applet.*;
………………….
………………….
public class appletclassnaame extends Applet
{
…………………..
…………………..
public void paint(Graphics G)
{
………………….
…………………. // Applet operations code
}
…………………..
…………………..
}
The appletclassname is the main class for the applet. When the applet is loaded, Java
creates an instance of the class, and then a series of Applet class methods are called on
that instance to execute the code.
Example:
init() method
The init() method is the first method to be called.
Variable declaration and initialization operations are performed in this method.
This method is called only once during the run time of our applet.
The general form is:
public void init()
{
…………
………… (Action)
…………
}
start() method
The start() method is called after init().
The start() method contains the actual code of the applet that should run.
It also executes whenever the applet is restored, maximized or moving from one tab to
another tab in the browser.
The general form is:
public void start()
{
…………
………… (Action)
…………
}
stop() method
The stop() method stops the execution of the applet.
The stop() method executes when the applet is minimized or when moving from one tab
to another in the browser.
The general form is:
public void stop()
{
…………
………… (Action)
…………
}
destroy() method
The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed.
The stop() method is always called before destroy(). The destroy() method removes the
applet object from memory.
The general form is:
public void destroy()
{
…………
………… (Action)
…………
}
paint()
The paint() method is used to redraw the output on the applet display area.
The paint() method executes after the execution of start() method and whenever the
applet or browser is resized.
The general form is:
public void paint(Graphics g)
{
…………
………… (Display statements)
…………
}
Example:
Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed
update()
This method is called when the applet has requested that a portion of its window be
redrawn.
The default version of update() first fills an applet with the default background color and
then calls paint().
If we fill the background using different color in paint(), the user will experience a flash
of the default background each time update() is called – that is, whenever the window is
repainted.
One way to avoid is to override the update() method so that it performs all necessary
display activities.
Example:
// Java program using update() method
import java.awt.*;
import java.applet.*;
/*
<applet code=PaintTest width=100 height=100>
</applet>
*/
public class PaintTest extends Applet
{
public void paint(Graphics g)
{
System.out.println("In paint");
}
public void update(Graphics g)
{
System.out.println("In update");
}
}
Here, message is the string to be output beginning at x, y. In a Java window, the upper left
corner is location 0, 0. The drawString method will not recognize newline characters. If
we want to start a line of text on another line, we must do so manually, specifying the
precise x, y locations where we want the line to begin.
setBackground()
The setBackground() method is used to change the background color of an applet’s
window.
This method is defined by the Component class.
The general form is:
void setBackground(Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
Example:
setBackground(Color.green);
setForeground()
The setForeground() method is used to change the color of the text in the applet’s
window. This method is defined by the Component class.
The general form is:
void setForeground(Color newColor)
Here, newColor specifies the new color.
Example:
setForeground(Color.red);
A good place to set the foreground and background colors is in the init() method. The
default foreground color is black. The default background color is light gray.
getBackground()
The getBackground() method is used to obtain the current settings for the background
color.
This method is also defined by the Component class. The general form is:
Color getBackground()
getForeground()
The getForeground() method is used to obtain the current settings for the foreground
color.
This method is also defined by the Component class. The general form is:
Color getForeground()
Example:
// A simple applet that sets the foreground and background colors and outputs a
string
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet
{
String msg;
// Set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg="Inside init() –";
}
// Initialize the string to be displayed.
public void start()
{
msg+="Inside start()..";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg+="Inside paint().";
g.drawString(msg, 10, 30);
}
}
Output:
Requesting Repainting
repaint()
The repaint() method causes the AWT runtime system to execute the update() method of
the Component class which clears the window with the background color of the applet
and then calls the paint() method.
The repaint() method has four forms. The simplest version of repaint() is shown here:
void repaint()
This version causes the entire window to be repainted. The following version specifies a
region that will be repainted:
void repaint(int left, int top, int width, int height)
Here, the coordinates of the upper-left corner of the region are specified by left and top,
and the width and height of the region are passed in width and height. These dimensions
are specified in pixels.
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height )
Here, maxDelay specifies the maximum number of milliseconds that can elapse before
update() is called. If the time elapses before update() can be called, it isn’t called. There is
no return value or exception thrown, so we must be careful.
14.8 Development and Execution of a Simple Applet
The development and execution of an Applet involves the following steps:
1) Writing the applet’s code (.java file)
2) Compiling the applet’s code (.class file will be ready after compilation)
3) Writing the HTML code (.html file)
4) Invoking the appletviewer utility from a command shell window
Writing the applet’s code
// Java program to create an Applet
// HelloApplets.java
import java.awt.*;
import java.applet.*;
Javac HelloApplets.java
2. The compiled output file called HelloApplets.class is placed in the same directory as the
source.
3. If any error message is received, then we must check for errors, correct them and compile
the applet again.
Writing the HTML code
The code for the HelloApplets.html file shall be keyed in, as shown here:
<html>
<head>
<title>Hello World !</title>
</head>
<body>
<applet code=”HelloApplets.class” width=400 height=200>
</applet>
</body>
</html>
Invoking the appletviewer utility from a command shell window
The appletviewer is available as part of the Java Development Kit that we have been using
so far.
We can use it to run our applet as follows:
appletviewer HelloApplets.html
The showStatus() method is used to display a message in the status window of the
browser or applet viewer on which the applet is running.
The status window is a good place to give the user feedback about what is occurring in
the applet, suggest options, or possibly report some types of errors.
The status window also makes an excellent debugging aid, because it gives an easy way
to output information about our applet.
Example:
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.",10,20);
showStatus("This is shown in the status window.");
}
}
14.10 The APPLET Tag
The <APPLET> tag is used to incorporate an applet into a web page.
The <APPLET> tag creates a space of the required size and then displays the applet output
in that space.
The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
An applet viewer will execute each APPLET tag that it finds in a separate window, while
web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many
applets on a single page.
The syntax for the standard Applet tag is shown here. Bracketed items are
optional.
<APPLET
[CODEBASE=codebase_URL]
CODE=AppletFileName.class
[ALT=alternate_text]
[NAME=applet_instance_name]
WIDTH=pixels
HEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels]
[HSPACE=pixels]
>
[<PARAM NAME=name1 VALUE=value1>]
[<PARAM NAME=name2 VALUE=value2>]
………………
………………
[Text to be displayed in the absence of Java]
</APPLET>
CODE=AppletFileName.class
WIDTH=pixels
HEIGHT=pixels
The attributes of the APPLET tag are as follows:
Attribute Meaning
CODEBASE= codebase_URL Specifies the URL of the directory in which the applet
resides. If the applet resides in the same directory as
the HTML file, then the CODEBASE attribute may be
omitted entirely.
CODE= AppletFileName.class CODE is a required attribute that gives the name of the
file containing our applet’s compiled .class file. This
file is relative to the code base URL of the applet,
which is the directory that the HTML file was in or the
directory indicated by CODEBASE if set.
ALT=alternate_text The ALT tag is an optional attribute used to specify a
short text message that should be displayed if the
browser understands the APPLET tag but can’t
currently run Java applets.
NAME=applet_instance_name A name for the applet may optionally be specified so
that other applets on the page may refer to this applet.
This facilitates inter-applet communication.
WIDTH=pixels WIDTH and HEIGHT are required attributes that give
HEIGHT=pixels the size (in pixels) of the applet display area.
ALIGN=alignment ALIGN is an optional attribute that specifies the
alignment of the applet. Possible values are: LEFT,
RIGHT, TOP, BOTTOM, MIDDLE, BASELINE,
TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE=pixels VSPACE specifies the amount of vertical blank space,
in pixels, above and below the applet. Used only when
some vertical alignment is specified with the ALIGN
attribute (TOP, BOTTOM, etc.). This attribute is
optional.
HSPACE=pixels HSPACE specifies the amount of horizontal blank
space, in pixels, on each side of the applet. Used only
when ALIGN is set to LEFT or RIGHT. This attribute
is optional.
PARAM NAME and VALUE The PARAM tag allows us to specify applet-specific
arguments in an HTML page. Applets access their
attributes with the getParameter() method.
Save this file as HelloJavaParam.html and then run the applet using the applet viewer as
follows:
appletviewer HelloJavaParam.html
14.12 Displaying Numeric Values
In applets, we can display numerical values by first converting them into strings and then
using the drawString() method of Graphics class.
We can do this easily by calling the valueOf() method of String class.
Example:
Applets work in a graphical environment. Therefore, applets treat inputs as text strings.
We must first create an area of the screen in which user can type and edit input items
(which may be any data type).
We can do this by using the TextField class of the applet package. Once text fields are
created for receiving input, we can type the values in the fields and edit them, if necessary.
Example:
Method Description
clearRect() Erases a rectangular area of the canvas.
copyArea() Copies a rectangular area of the canvas to another area.
drawArc() Draws a hollow arc.
drawLine() Draws a straight line.
drawOval() Draws a hollow oval.
drawPolygon() Draws a hollow polygon.
drawRect() Draws a hollow rectangle.
drawRoundRect() Draws a hollow rectangle with rounded corners.
drawString() Displays a text string.
fillArc() Draws a filled arc.
fillOval() Draws a filled oval.
fillPolygon() Draws a filled polygon.
fillRect() Draws a filled rectangle.
fillRoundRect() Draws a filled rectangle with rounded corners.
getColor() Retrieves the current drawing color.
getFont() Retrieves the currently used font.
getFontMetrics() Retrieves information about the current font.
setColor() Sets the drawing color.
setFont() Sets the font.
drawRect()
will draw a rectangle starting at (10, 60) having a width of 40 pixels and a height of 30
pixels. The drawRect() method draws only the outline of a box.
fillRect()
The fillRect() method is used to draw a solid box.
This also takes four parameters corresponding to the starting point, the width and the
height of the rectangle.
For example, the statement
g.fillRect(60, 10, 30, 80);
Applet
Applet Started
Output:
14.17 Drawing Arcs
drawArc() & fillArc()
The drawArc() method is used to draw an arc.
The drawArc() designed to draw arcs takes six arguments. The first four are the same as
the arguments for drawOval() method and the last two represent the starting angle of the
arc and the number of degrees around the arc.
The fillArc() method is used to fill anarc.Filled arcs are drawnas if they were sections of
a pie.
Example:
Output:
Write a Java program to draw a human face.
Example: