Download Unit-5 - CBIT MCA | Home

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

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

Document related concepts
no text concepts found
Transcript
Applet
Applet is a special type of program that is embedded in the
webpage to generate the dynamic content. It runs inside the
browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:



It works at client side so less response time.
Secured
It can be executed by browsers running under many
plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet

Plugin is required at client browser to execute applet.
What is Java Plug-in software?
The Java Plug-in software is a component of the Java Runtime
Environment (JRE). The JRE allows applets written in the Java
programming language to run inside various browsers. The Java
Plug-in software is not a standalone program and cannot be
installed separately.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel.
Panel class extends Container which is the subclass of
Component.
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an
applet.
java.applet.Applet class:
For creating any applet java.applet.Applet class must be
inherited. It provides 4 life cycle methods of applet.

init: This method is intended for whatever initialization is
needed for your applet. It is called after the param tags
inside the applet tag have been processed.


start: is invoked after the init() method or browser is
maximized. It is used to start the Applet
stop: : is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.


destroy: This method is only called when the browser
shuts down normally. Because applets are meant to live on
an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and
also any time the applet needs to repaint itself in the
browser. The paint() method is actually inherited from the
java.awt.
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.
These include methods that do the following:








Get applet parameters
Get the network location of the HTML file that contains the
applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip
Play an audio clip
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/browser may:






request information about the author, version and copyright
of the applet
request a description of the parameters the applet
recognizes
initialize the applet
destroy the applet
start the applet's execution
stop the applet's execution
The Applet class provides default implementations of each of
these methods. Those implementations may be overridden as
necessary.
java.awt.Component class:
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet.
It provides Graphics class object that can be used for
drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an
applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile
it. After that create an html file and place the applet code in html
file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet
5. {
6. public void paint(Graphics g)
7. {
8. g.drawString("welcome",150,150);
9. }
10.
}
Note: class must be public because its object is created by
Java Plugin software that resides on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that
contains applet tag in comment and compile it. After that run it
by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet
5. {
6. public void paint(Graphics g)
7. {
8. g.drawString("welcome to applet",150,150);
9. }
10.
11.
}
12.
/*
13.
<applet code="First.class" width="300" height="300"
>
14.
</applet>
15.
*/
To execute the applet by appletviewer tool, write in command
prompt:
c:\>javac First.java
c:\>appletviewer First.java
The HTML APPLET Tag
The syntax for a fuller form of the APPLET tag is shown here.
Bracketed items are
optional.
< 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>
Let’s take a look at each part now.
CODEBASE CODEBASE is an optional attribute that
specifies the base URL of the applet
code, which is the directory that will be searched for the
applet’s executable class file
(specified by the CODE tag). The HTML document’s URL
directory is used as the CODEBASE if this attribute is not
specified. The CODEBASE does not have to be on the host
from which the HTML document was read.
CODE CODE is a required attribute that gives the name of
the file containing your 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 The ALT tag is an optional attribute used to specify a
short text message that should
be displayed if the browser recognizes the APPLET tag but
can’t currently run Java applets.
This is distinct from the alternate HTML you provide for
browsers that don’t support applets.
NAME NAME is an optional attribute used to specify a
name for the applet instance.
Applets must be named in order for other applets on the
same page to find them by name
and communicate with them. To obtain an applet by name,
use getApplet( ), which is defined
by the AppletContext interface.
WIDTH and HEIGHT WIDTH and HEIGHT are required
attributes that give the size (in pixels)
of the applet display area.
Parameter in Applet
We can supply user defined parameters to an applet using
<PARAM…> tags.
Each <PARAM…> tag has a name attribute such as color, and
value attribute such as red.
Inside the applet code, the applet can refer to that parameter by a
name to find its value.
We can get any information from the HTML file as a parameter.
For this purpose, Applet class provides a method named
getParameter().
Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet
5. {
6. public void paint(Graphics g)
7. {
8. String str=getParameter("msg");
9. g.drawString(str,50, 50);
10.
}
11.
12.
}
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Displaying numerical values: 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.
Ex: sum of two no.
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics
programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used
to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws
a rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height):
is used to fill rectangle with the default color and specified
width and height.
4. public abstract void drawOval(int x, int y, int width, int
height): is used to draw oval with the specified width and
height.
5. public abstract void fillOval(int x, int y, int width, int height):
is used to fill oval with the default color and specified width
and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is
used to draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
10.
public abstract void setColor(Color c): is used to set the
graphics current color to the specified color.
11.
public abstract void setFont(Font font): is used to set
the graphics current font to the specified font.
Example of Graphics in applet:
1. import java.applet.Applet;
2. import java.awt.*;
3. public class GraphicsDemo extends Applet
4. {
5. public void paint(Graphics g)
6. {
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10.
g.drawRect(70,100,30,30);
11.
12.
13.
14.
15.
16.
17.
18.
19.
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300
">
4. </applet>
5. </body>
6. </html>
Painting in Applet
We can perform painting operation in applet by the
mouseDragged() method of MouseMotionListener interface
Example of Painting in Applet:
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMo
tionListener
5. {
6. public void init()
7. {
8. addMouseMotionListener(this);
9. setBackground(Color.red);
10.
}
11.
public void mouseDragged(MouseEvent me)
12.
{
13.
Graphics g=getGraphics();
14.
g.setColor(Color.white);
15.
g.fillOval(me.getX(),me.getY(),5,5);
16.
}
17.
public void mouseMoved(MouseEvent me){}
18.
19.
}
In the above example, getX() and getY() method of MouseEvent is
used to get the current x-axis and y-axis. The getGraphics() method
of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose
image is required to be displayed. The java.awt.Graphics class
provide a method drawImage() to display the image.
An applet can display images of the format GIF, JPEG, BMP,
and others.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
How to get the object of Image:
The java.applet.Applet class provides getImage() method that
returns the object of image.
Syntax:
1. public Image getImage(URL u, String image){}
getDocumentBase( ) and getCodeBase( )
Java will allow the applet to load data from the directory
holding the HTML file that started the
applet (the document base) and the directory from which the
applet’s class file was loaded
(the code base).
These directories are returned as URL objects by
getDocumentBase( ) and getCodeBase( ). They can be
concatenated with a string that names the file you want to load.
To actually load another file, you will use the showDocument( )
method defined by the AppletContext interface,
The following applet illustrates these methods:
// Display code and document bases.
import java.awt.*;
2.
import java.applet.*;
3.
import java.net.*;
4.
/*
5.
<applet code="Bases" width=300
height=50>
6.
</applet>
7.
*/
8.
public class Bases extends Applet
9.
{
10. // Display code and document bases.
11. public void paint(Graphics g)
12.
{
13. String msg;
14. URL url = getCodeBase(); // get code
base
15. msg = "Code base: " +
url.toString();
16. g.drawString(msg, 10, 20);
17. url = getDocumentBase(); // get
document base
18. msg = "Document base: " +
url.toString();
19. g.drawString(msg, 10, 40);
20. }
21. }
Sample output from this program is shown
Other required methods of Applet class to display
image:
1. public URL getDocumentBase(): is used to return the URL of
the document in which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
Example of displaying image in applet:
1. import java.awt.*;
2. import java.applet.*;
3. public class DisplayImage extends Applet
4. {
5. Image picture;
6. public void init()
7. {
8. picture = getImage(getDocumentBase(),"sonoo.jpg");
9. }
10.
public void paint(Graphics g)
11.
{
12.
g.drawImage(picture, 30,30, this);
13.
}
14.
}
In the above example, drawImage() method of Graphics class is
used to display the image. The 4th argument of drawImage()
method of is ImageObserver object.
The Component class implements ImageObserver interface. So
current class object would also be treated as ImageObserver
because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300"
>
4. </applet>
5. </body>
6. </html>
Example of animation in applet:
1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet
4. {
5.
6. Image picture;
7.
8. public void init()
9. {
10.
picture =getImage(getDocumentBase(),"bike_1.gif");
11.
}
12.
13.
public void paint(Graphics g)
14.
{
15.
for(int i=0;i<500;i++)
16.
{
17.
g.drawImage(picture, i,30, this);
18.
19.
Try
20.
{
21.
Thread.sleep(100);
22.
}
23.
catch(Exception e){}
24.
}
25.
}
26.
}
Playing Audio:
An applet can play an audio file represented by the AudioClip
interface in the java.applet package.
The AudioClip interface has three methods, including:



public void play(): Plays the audio clip one time, from the
beginning.
public void loop(): Causes the audio clip to replay
continually.
public void stop(): Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the
getAudioClip() method of the Applet class. The getAudioClip()
method returns immediately, whether or not the URL resolves to
an actual audio file. The audio file is not downloaded until an
attempt is made to play the audio clip.
Following is the example showing all the steps to play an audio:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL =
this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new
URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load
audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}
Now, let us call this applet as follows:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0"
height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
</html>
You can use your test.wav at your PC to test the above example.
Applet Communication
java.applet.AppletContext class provides the facility of
communication between applets.
We provide the name of applet through the HTML file. It
provides getApplet() method that returns the object of Applet.
Syntax:
1. public Applet getApplet(String name){}
Example of Applet Communication
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionL
istener
5. {
6. Button b;
7.
8. public void init()
9. {
10.
b=new Button("Click");
11.
b.setBounds(50,50,60,50);
12.
13.
add(b);
14.
b.addActionListener(this);
15.
}
16.
17.
public void actionPerformed(ActionEvent e)
18.
{
19.
20.
AppletContext ctx=getAppletContext();
21.
Applet a=ctx.getApplet("app2");
22.
a.setBackground(Color.yellow);
23.
}
24.
}
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150
" name="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="
app2">
7. </applet>
8. </body>
9. </html>
Creating your own appletviewer
As you know well that appletviewer tool creates a frame and
displays the output of applet in the frame.
You can also create your frame and display the applet output.
Example that works like appletviewer tool
Let's see the simple example that works like appletviewer tool.
This example displays applet on the frame.
1. import java.applet.Applet;
2. import java.awt.Frame;
3. import java.awt.Graphics;
4.
5. public class MyViewer extends Frame{
6. public static void main(String[] args) throws Exception{
7. Class c=Class.forName(args[0]);
8.
9. MyViewer v=new MyViewer();
10.
v.setSize(400,400);
11.
v.setLayout(null);
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
v.setVisible(true);
Applet a=(Applet)c.newInstance();
a.start();
Graphics g=v.getGraphics();
a.paint(g);
a.stop();
}
}
1. //simple program of applet
2.
3. import java.applet.Applet;
4. import java.awt.Graphics;
5.
6. public class First extends Applet{
7.
8. public void paint(Graphics g){g.drawString("Welcome",
50, 50);}
9. }
Output:
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have
all the controls of swing. The JApplet class extends the Applet class.
Example of EventHandling in JApplet:
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionLi
stener
5. {
6. JButton b;
7. JTextField tf;
8. public void init()
9. {
10.
tf=new JTextField();
11.
tf.setBounds(30,40,150,20);
12.
b=new JButton("Click");
13.
b.setBounds(80,150,70,40);
14.
add(b);add(tf);
15.
b.addActionListener(this);
16.
setLayout(null);
17.
}
18.
19.
public void actionPerformed(ActionEvent e){
20.
tf.setText("Welcome");
21.
}
22.
}
In the above example, we have created all the controls in init()
method because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300"
>
4. </applet>
5. </body>
6. </html>