Download Chapter9 - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
APPLETS AND APPLICATIONS
9
9.1 The applet class
9.2 Applets and HTML (The applet Tag)
9.3 Life cycles of an applet
9.4 Graphics class
Drawstring, drawline, drawrect, fillrect, clearrect, fillroundrect, drawovall
9.5 Painting the applet
Update, paint, repaint method
9.6 Passing parameters to applets getparameter () method
 Introduction:
An applet is a special type of Java program that can be embedded in a
internet application and runs on a web browser.
The applets reside in a server and they can be downloaded from the server to
the client machine and executed on client machine if the browser is enabled
with Java technology.
An applet is a Java class that extends the java.applet.Applet class.
A main () method is not invoked on an applet, and an applet class will not
define main ().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be
followed.
Applets are basically of two types:
(1) Local Applet: These are applets which are created for standalone PC's
where the same PC is distinguished as server and client. Hence, to execute a
local applet there is no need of internet connection.
(2) Remote Applet: The applets which are developed for an environment
where the server and the client machine are physically apart from each other
are called remote applets. In order to locate and load the remote applet we
must know the applet address on the web. This address is known as the URL.
The difference between a Java applet and a Java application is that a
Java application runs standalone, i.e. outside the browser while an applet
runs in the context of a web browser, embedded within an HTML page.
Second an applet does not have main () method while Java application starts
with main () method.
Why Use Applet with HTML? or Need for Applet:
Applet allows you to create dynamic web pages. Using HTML we can create
only static pages.
9.1 The applet class
Every applet is an extension of the java.applet.Applet class. The base Applet
class provides methods that a derived Applet class may call to obtain
information and services from the browser context.
It include methods that do the following:
(1) Get applet parameters
(2) Get the network location of the HTML file that contains the applet
(3) Get the network location of the applet class directory
(4) Print a status message in the browser
(5) Fetch an image
(6) Fetch an audio clip
(7) Play an audio clip
(8) Resize the applet
Additionally, the Applet class provides an interface by which the viewer or
browser obtains information about the applet and controls the applet's
execution. The viewer may:
(1) Request information about the author, version and copyright of the
applet.
(2) Request a description of the parameters the applet recognizes
(3) Initialize the applet
(4) Destroy the applet
(5) Start the applet's execution
(6) Stop the applet's execution
The Applet class provides default implementations of each of these methods.
Those implementations may be overridden as necessary.
9.2 Applets and HTML (The applet Tag)
An applet is a program that can be referenced by the HTML document. You
can incorporate an applet in your HTML application using APPLET tag that is
supported by HTML.
When you run the HTML application that contains applet, an applet is
downloaded from the web server and it is executed in the browser that can
supports applet.
In order to add an applet in your HTML application you need to use APPLET
tag in HTML application. The general syntax of an APPLET tag is given below:
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
Following is the detailed description of all the attributes of the APPLET tag:
(1) CODEBASE:
 It is an optional attribute. It specifies the URL of the applet code.
 If you specify the CODEBASE attribute then it will be searched first to
locate the applet’s executable class file.
 If it is not specified then the directory of HTML document is used as
the CODEBASE directory by default.
(2) CODE:
 It is not an optional attribute you must specify this attribute.
 It contains the name of the applets .class file.
(3) ALT:
 It is an optional attribute.
 It contains a text that is displayed if the browser understands the
APPLET tag but can’t currently run Java applets.
(4) NAME:
 It is an optional attribute. It is used to specify a name for the applet.
 It is useful to identify and communicate the applet if HTML application
contains more then one applet.
 You can retrieve the name of the applet by using getApplet ( )
method which is defined in the AppletContext interface.
(5) WIDTH AND HEIGHT:
 WIDTH and HEIGHT both are the compulsory attributes.
 It specifies the size of the applet on HTML application.
 Both are specified in terms of pixels.
(6) ALIGN:
 It is an optional attribute that is used to specify the alignment of the
applet.
 You can set the alignment of the applet using one of the following
values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE, and ABSBOTTOM.
(7) VSPACE AND HSPACE:
 VSPACE AND HSPACE both are optional attributes.
 VSPACE specifies the space, in pixels, above and below the applet.
 HSPACE specifies the space, in pixels, on each side of the applet.
(8) PARAM NAME AND VALUE:
 PARAM tag allows you to pass arguments to an applet from HTML
application. It has two attributes named NAME and VALUE.
 You can retrieve the arguments passed using PARAM tag in applet
using getParameter () method.
 The NAME attribute specifies name of the argument and VALUE tag
specifies value for that argument.
9.3 Life cycles of an applet
An applet can pass through following states during its Life cycle as shown in
the figure.
init ()
Born
State
stop ()
start ()
Running
State
Idle
State
destroy ()
start ()
Dead
State
(1) Born: When the applet program is executed on the browser init ()
method of the applet is called automatically. At this stage an applet is said
to be in born state. This state is also called initialization state. During the
applet life cycle, the born state occurs only once. The init function is defined
within an applet. However, it can be overridden by the program. This
function is used to initialize instance members, to load the required fonts, to
initialize objects, to load pictures, to load back colors, etc.
(2) Running: After initialization, this state will automatically occur by
invoking the start method of applet class which again calls the run method
and which calls the paint method. The running state also occurs from idle
state when the applet is reloaded.
(3) Idle: The idle state will make the execution of the applet to be halted
temporarily. Applet moves to this state when the currently executed applet
is minimized or when the user switches over to another page. At this point
the stop method is invoked. From the idle state the applet can move to the
running state.
(4) Dead: When the applet programs terminate, the destroy function is
invoked which makes an applet to be in dead state.
Following are the methods used for navigating between various states of the
applet.
(1) init () method:
The life cycle of an applet begins when the applet is loaded first time into
the browser.
When the applet is loaded first time into the browser it call the init ()
method.
This method is called only once during the life cycle of an applet.
This method provides an appropriate place for initialization of the variables
required and other set up operations such as setting of background color,
defining the applet’s layout, parsing parameters, etc.
This method is normally used to retrieve the parameters from an HTML
application that is passed using the PARAM tag of HTML. We can use the
getParameter () method in the init () method to retrieve parameter from
HTML application.
(2) Start () method:
This method is called after the init () method is called to start the applet by
the browser.
You can call this method as many times as required. It is normally used to
start the applet. User can interact with the applet only when the applet is
start.
The difference between the start () method and the init () method is that
init () method is called only once when the page is loaded, while start ()
method is called every time the page is loaded and every time the page is
restarted. That is, if a user navigated from one page to another page and
then he returns to the original page, start () method is called again but the
init () method is not called again.
(3) Stop () method:
This method is called each time the user navigates from one page to
another page.
It is always advisable to use stop () method if any type of animation or
memory consuming activities is being performed in order to avoid wasting
of system resources.
(4) destroy () method:
This method is called immediately before the applet exits.
The exiting operation is caused by either the applet operation requesting
for the exit or may be the web browser is shut down.
When it is called it directs the applet to free up all the system resources
being used by it.
9.4 Graphics class
The Graphics class provides framework for all graphics operations within
the AWT. It plays two different, but related, roles.
First one is the graphics context. The graphics context is information that
will affect drawing operations. This includes the background and foreground
colors, the font, and the location and dimensions of the clipping rectangle
(the region of a component in which graphics can be drawn). It even
includes information about the eventual destination of the graphics
operations themselves (screen or image).
Second, the Graphics class provides methods for drawing simple geometric
shapes, text, and images to the graphics destination. All output to the
graphics destination occurs via an invocation of one of these methods.
In order to draw, a program requires a valid graphics context which is
represented by an instance of the Graphics class.
Hence the Graphics class is an abstract base class, you cannot crate an
instance of the Graphics class directly. An instance is generally created by a
component, and passed to the program as an argument to the component's
update () and paint () methods.
Graphics Coordinate System for AWT:
A coordinate system is a method for unambiguously specifying the location
of points in space.
In the case of the AWT, this space is a two-dimensional surface called a
plane.
Each location in a plane can be specified by two integers, called the x and y
coordinates.
The values of the x and y coordinates are calculated in terms of the point's
respective horizontal and vertical displacement from the origin.
In the case of the AWT, the origin is always the point in the upper-left
corner of the plane. It has the coordinate values 0 (for x) and 0 (for y).
The illustration in Figure shows two points one located at the origin, and
another located at a position five across and seven down from the origin.
Following are the Graphics class methods:
(1) drawString:
This method allows you to draw a string with default font and default
color.
In order to display string on the applet you need to specify the X and Y
Coordinate position of the first character of the string. This means you
need to specify the position from which the string will display on the
applet.
Syntax:
Void drawString (String S, int X, int Y);
Here,
S is the string that you want to display.
X is the X Coordinate position of first character of string.
Y is the Y Coordinate position of first character of string.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawString("WELCOME TO MY HOME",10,20);
}
}
Output:
(2) drawLine:
This method allows you to draw a line.
In order to draw the line you need to specify the X and Y coordinate
position of the two points that creates a line.
This method draw a line between two points specified as an argument
with default color which is black.
Syntax:
drawLine (int X1, int Y1, int X2, int Y2);
Here,
X1 is the X- Coordinate of the first point.
Y1 is the Y- Coordinate of the first point.
X2 is the X- Coordinate of the second point.
Y2 is the Y- Coordinate of the second point.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawLine(10,10,200,200);
}
}
Output:
(3) drawRect:
This method allows you to draw a rectangle with outlined border
without filling any color inside the rectangle.
In order to draw the rectangle you need to specify the X Coordinate
position and Y Coordinate position of the top-left corner of the
rectangle along with width and height.
This method draw rectangle with default border color which is black.
Syntax:
Void drawRect (int X, int Y, int Width, Int Height);
Here,
X is the X Coordinate position of the top-left corner of the rectangle.
Y is the Y Coordinate position of the top-left corner of the rectangle.
Width is the width of the rectangle to be draw.
Height is the height of the rectangle to be draw.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawRect(20,20,100,200);
}
}
Output:
(4) fillRect:
This method allows you to draw a rectangle that is filled with default
color which is black.
In order to draw the filled rectangle you need to specify the X
Coordinate position and Y Coordinate position of the top-left corner of
the rectangle along with width and height.
Syntax:
Void fillRect (int X, int Y, int Width, Int Height);
Here,
X is the X Coordinate position of the top-left corner of the rectangle.
Y is the Y Coordinate position of the top-left corner of the rectangle.
Width is the width of the rectangle to be draw.
Height is the height of the rectangle to be draw.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.fillRect (20, 20,100,100);
}
}
Output:
(5) clearRect:
This method allows you to clears the specified rectangle by filling it
with the background color of the current drawing surface.
In order to clear the specific area of the rectangle that is drawn
previously using drawRect() or fillRect() method you need to specify
the X Coordinate position and Y Coordinate position of the top-left
corner from which you want to clear the rectangle along with the width
and height.
Syntax:
Void clearRect (int X, int Y, int Width, int Height);
Here,
X is the X Coordinate position of the top-left corner of the rectangle
from which you want to clear the rectangle.
Y is the Y Coordinate position of the top-left corner of the rectangle
from which you want to clear the rectangle.
Width and Height specifies the portion of the rectangle to be cleared
from top-left corner specified.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.fillRect (10, 10,100,200);
g.clearRect (10, 30, 100, 10);
}
}
Output:
Before clearRect is called:
After clearRect is called:
(6) drawRoundRect:
This method allows you to draw a rounded rectangle with outlined
border without filling any color inside the rounded rectangle.
In order to draw rounded rectangle you need to specify the X
Coordinate position and Y Coordinate position of the top-left corner of
the rounded rectangle along with width, height, arc width and arc
height.
Syntax:
Void drawRoundRect (int X, int Y, int Width, int Height, int arcWidth,
int arcHeight);
Here,
X is the X Coordinate position of the top-left corner of the rounded
rectangle.
Y is the Y Coordinate position of the top-left corner of the rounded
rectangle.
Width is the width of the rounded rectangle to be draw.
Height is the height of the rounded rectangle to be draw.
arcWidth is the horizontal diameter of the arc to be drawn at four
side of the rounded rectangle.
arcHeight is the vertical diameter of the arc to be drawn at four side
of the rounded rectangle.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawRoundRect (10, 10, 300, 100, 50, 30);
}
}
Output:
(7) fillRoundRect:
This method allows you to draw filled rounded rectangle which is filled
with default color black.
In order to draw filled rounded rectangle you need to specify the X
Coordinate position and Y Coordinate position of the top-left corner of the
rounded rectangle along with width, height, arc width and arc height.
Syntax:
Void fillRoundRect (int X, int Y, int Width, int Height, int arcWidth, int
arcHeight);
Here,
X is the X Coordinate position of the top-left corner of the rounded
rectangle.
Y is the Y Coordinate position of the top-left corner of the rounded
rectangle.
Width is the width of the rounded rectangle to be draw.
Height is the height of the rounded rectangle to be draw.
arcWidth is the horizontal diameter of the arc to be drawn at four side of
the rounded rectangle.
arcHeight is the vertical diameter of the arc to be drawn at four side of
the rounded rectangle.
Example:
import java.awt.*;
import java.applet.*;
Public class Graph extends Applet
{
Public void init ()
{
}
Public void paint (Graphics g)
{
g.fillRoundRect (10, 10, 300, 100, 50, 30);
}
}
Output:
(8) drawOval:
This method allows you to draw an outlined oval without filling any color.
The default color of the outline is black.
In order to draw an oval you need to specify X Coordinate position and Y
Coordinate position of the top-left corner of the rectangle along with the
width and height of the rectangle. It will draw an oval that can fit into the
area specified by the rectangle.
You can also draw an ellipse and a circle using this method.
If the arguments that you pass to the method specifies the rectangular
area then it will draw an ellipse that can fit into the area surrounded by
rectangle.
If the arguments that you pass to the method specifies the square area
then it will draw a circle that can fit into the area surrounded by square.
Syntax:
Void drawOval (int X, int Y, int Width, int Height);
Here,
X is the X Coordinate position of the top-left corner of the rectangle.
Y is the Y Coordinate position of the top-left corner of the rectangle.
Width is the width of the rectangle.
Height is the height of the rectangle.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawOval (10, 10,200,100);
g.drawOval (50,150,100,100);
}
}
Output:
(9) fillOval:
This method allows you to draw an oval that is filled with default color that
is black.
In order to draw a filled oval you need to specify X Coordinate position
and Y Coordinate position of the top-left corner of the rectangle along with
the width and height of the rectangle. It will draw a filled oval that can fit
into the area specified by the rectangle.
You can also draw filled ellipse and filled circle using this method.
If the arguments that you pass to the method specifies the rectangular
area then it will draw filled ellipse that can fit into the area surrounded by
rectangle.
If the arguments that you pass to the method specifies the square area
then it will draw filled circle that can fit into the area surrounded by
square.
Syntax:
Void drawOval (int X, int Y, int Width, int Height);
Here,
X is the X Coordinate position of the top-left corner of the rectangle.
Y is the Y Coordinate position of the top-left corner of the rectangle.
Width is the width of the rectangle.
Height is the height of the rectangle.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.fillOval(10,10,200,100);
g.fillOval(50,150,100,100);
}
}
Output:
(10) drawPolygon:
This method allows you to draw an outlined polygon without filling any
color.
The default color for the outline of the polygon is black.
In order to draw an outlined polygon you have to specify an array of X
Coordinate and Y Coordinate of the points that construct the polygon.
Syntax:
Void drawPolygon (int [] xPoint, int [] yPoint, int NumPoint);
Here,
xPoint is an array of X Coordinate position of all the points in the
polygon.
yPoint is an array of Y Coordinate position of all the points in the polygon.
NumPoint is the total number of points in the polygon.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
int xPoints[] = {200, 110, 200, 175};
int yPoints[] = {20, 70, 108, 63};
int NumPoint = 4;
g.drawPolygon (xPoints, yPoints, NumPoint);
}
}
Output:
(11) fillPolygon:
This method allows you to draw a filled polygon with default color that is
black.
In order to draw a filled polygon you have to specify an array of X
Coordinate and Y Coordinate of the points that construct the polygon.
Syntax:
Void fillPolygon (int [] xPoint, int [] yPoint, int NumPoint);
Here,
xPoint is an array of X Coordinate position of all the points in the
polygon.
yPoint is an array of Y Coordinate position of all the points in the polygon.
NumPoint is the total number of points in the polygon.
Example:
import java.awt.*;
import java.applet.*;
public class Graph extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
int xPoints[] = {200, 110, 200, 175};
int yPoints[] = {20, 70, 108, 63};
int NumPoint = 4;
g.fillPolygon (xPoints, yPoints, NumPoint);
}
}
Output:
9.5 Painting the applet (Update, paint, and repaint method)
(1) paint ( ):
paint () method is called when applet starts its execution.
The general form of paint () method is given below:
public void paint (Graphics g)
{
}
paint () method accepts Graphics class object as an argument. Using this
object you can call various Graphics class methods to draw images on applet.
For Example:
import java.awt.*;
import java.applet.*;
public class MethodsDemo1 extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawString("Welcome to Java!!", 50, 60 );
}
}
Output:
paint () method is also called automatically when it is required to redraw the
applet. For example if you minimize the applet or maximize the applet or if
certain portion of the applet is covered by some other application.
Thus paint () method is used to draw or redraw graphical output on applet.
(2) update ():
update () method is called when it is required to redraw some or entire
portion of applet.
If you wish you can override the default update () method as per your
requirement.
The default version of update () method first fill the applet with default
background color which is white and then call paint () method.
The general form of update method is given below:
public void update (Graphics g)
{
}
update () method accepts Graphics class object as an argument. Using this
object you can call various Graphics class methods to draw images on applet.
For Example:
import java.awt.*;
import java.applet.*;
public class MethodsDemo1 extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
g.drawString("Hello Mr. Pankaj Patel", 50, 40 );
update(g);
}
public void update(Graphics g)
{
setBackground(Color.red);
g.drawString("Welcome to Java!!", 50, 60 );
}
}
Output:
(3) repaint ():
repaint () method is called when it is required to update the information that
is displayed in the applet window.
When repaint () method is called it calls update () method which fills the
applet with default background color and then call paint () method.
repaint ()
update ()
paint ()
There are four different forms of repaint( ) method which are given below:
(1) void repaint ( ): This version causes the entire window to be repainted.
(2) void repaint (int left, int top, int width, int height): This version
causes specific portion of applet window to be repainted.
(3) void repaint (long Delay): This version causes the entire window to be
repainted after specific amount of time. The time you specify as a Delay must
be in millisecond.
(4) void repaint (long Delay, int x, int y, int width, int height): This
version causes specific portion of applet window to be repainted after specific
amount of time. The time you specify as a Delay must be in millisecond.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonDemo1 extends Applet
implements ActionListener
{
String msg;
public void init()
{
Button B1 = new Button ();
B1.setLabel("JAVA");
add (B1);
B1.addActionListener(this);
Button B2 = new Button ();
B2.setLabel(".NET");
add (B2);
B2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
if(str.equals("JAVA"))
{
msg = "You pressed JAVA";
}
else if (str.equals(".NET"))
{
msg = "You Pressed .NET";
}
repaint ();
}
public void paint (Graphics g)
{
g.drawString (msg, 6, 100);
}
}
Output:
9.6 Passing parameters to applets getparameter () method
It is possible to pass parameters to an applet program from your HTML
application. Many times when you're developing a Java applet, you want to
pass parameters from an HTML page to the applet you're invoking. For
instance, you may want to tell the applet what background color it should
use, or what font to use, to keep your Java applet consistent with the rest of
your HTML-based web site.
A great benefit of passing applet parameters from HTML pages to the applets
is portability. If you pass parameters into your Java applets, they can be
portable from one web page to another and from one web site to another. On
the other hand, if you don't pass parameters into a Java applet, how will the
applet know what font to use? Simple - you hardwire it into the Java source
code.
In order to pass parameters to an applet program from your HTML application
you have to use PARAM tag.
The general syntax of PARAM tag is given below:
< PARAM NAME = AttributeName VALUE = AttributeValue>
Here,
Name is the name of the parameter you want to pass to an applet program.
Value is the value for the parameter that you are passing to an applet
program.
The PARAM tag must be included between the <APPLET> and </APPLET> tag.
Consider the Following Example:
<HTML>
<HEAD>
<TITLE>Passing Parameter to applet</TITLE>
</HEAD>
<BODY>
<APPLET CODE="GetParameterDemo1.class" WIDTH="400"
HEIGHT="50">
<PARAM NAME="font" VALUE="Dialog">
<PARAM NAME="size" VALUE="24">
<PARAM NAME="string" VALUE="Welcome To Applet">
</APPLET>
</BODY>
</HTML>
In the above example the name of the class file that will retrieve the
parameter that you pass using PARAM tag is specified in the APPLET tag with
CODE parameter.
Once you pass parameters from HTML application it needs to be retrieved in
an applet program. You can retrieve parameters passed from HTML
application using getParameter () method in your applet.
Using getParameter () method you can retrieve the value of particular
parameter that is passed from HTML application using PARAM tag.
In order to retrieve the value of the parameter you have to specify the name
of the parameter as an argument to getParameter () method.
This method returns a value of type string. So if you pass any other type of
value then it is automatically converted into string type.
The general syntax of getParameter () method is given below:
String getParameter (String ParamName);
Consider the following example:
import java.awt.*;
import java.applet.*;
public class GetParameterDemo1 extends Applet
{
public void init()
{
}
public void paint(Graphics g)
{
String myFont = getParameter("font");
String myString = getParameter("string");
int mySize
= Integer.parseInt(getParameter("size"));
Font f = new Font(myFont, Font.BOLD, mySize);
g.setFont(f);
g.setColor(Color.red);
g.drawString(myString, 20, 20);
}
}
Output:
THE JAVA LIBRARY