Sie sind auf Seite 1von 55

Java Applet

JAVA PROGRAMMING
Prepared by Harsha Chauhan

Java Applet
AJava appletis a special kind ofJava program

that a browser enabled withJava technology can


download from the internet and run.
Anappletis typically embedded inside a web

page and runs in the context of a browser.


Anappletmust be a subclass of the

java.applet. Appletclass.

Prepared by Harsha Chauhan

Java Applet
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
platforms, including Linux, Windows, Mac Os etc.

Drawback of Applet
Plugin is required at client browser to execute applet.

Prepared by Harsha Chauhan

Java Applet
There are some important differences
between an applet and a standalone
Java application, including the following:
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.
Cond.

Prepared by Harsha Chauhan

Java Applet

contd.

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.

Prepared by Harsha Chauhan

Local and Remote Applets


Other classes that the applet needs can be
downloaded in a single Java Archive (JAR) file.
One of Java's major strengths is that you can
use the language to create dynamic content
for your Web pages.
That is, thanks to Java applets, your Web
pages are no longer limited to the tricks you
can perform with HTML.
Now your Web pages can do just about
anything you want them to. All you need to
do is write the appropriate applets.
Prepared by Harsha Chauhan

Local and Remote Applets


But writing Java applets is only half the story.
How your Web page's users obtain and run
the applets is equally as important.
It's up to you to not only write the applet (or
use someone else's applet), but also to
provide users access to the applet.
Basically, your Web pages can contain two
types of applets: local and remote.
In this section, you learn the difference
between these applet types, which are
named after the location at which they are
stored.
Prepared by Harsha Chauhan

Local Applets
Local Applets

A local applet is one that is stored on your


own computer system.
When your Web page must find a local
applet, it doesn't need to retrieve
information from the Internet-in fact, your
browser doesn't even need to be connected
to the Internet at that time.

Local applets are stored on and loaded fro


m your computer
system.
Prepared by Harsha Chauhan
8

Specifying a Local Applet.


<applet
codebase="tictactoe"

code="TicTacToe.class"

width=120

height=120>
</applet>
thecodebaseattribute specifies a path name on your
system for the local applet, whereas thecodeattribute
specifies the name of the byte-code file that contains the
applet's code. The path specified in thecodebaseattribute
is relative to the folder containing the HTML document that
references the applet.
Prepared by Harsha Chauhan

Remote Applet.
A remote applet is one that is located on another
computer system .
This computer system may be located in the
building next door or it may be on the other side of
the world-it makes no difference to your Javacompatible browser.
No matter where the remote applet is located, it's
downloaded onto your computer via the Internet.
Your browser must, of course, be connected to the
Internet at the time it needs to display the remote
applet.

Remote applets are stored on another system and ar
e down-loaded onto your computer via the Internet.
Prepared by Harsha Chauhan

10

Remote Applet.

Contd

To reference a remote applet in your Web page,


you must know the applet's URL (where it's
located on the Web) and any attributes and
parameters that you need to supply in order to
display the applet correctly.
If you didn't write the applet, you'll need to
find the document that describes the applet's
attributes and parameters.
This document is usually written by the applet's
author. how to compose an HTML<applet>tag
that accesses a remote applet.

Prepared by Harsha Chauhan

11

Specifying a Remote Applet.


<applet
codebase="http://www.myconnect.com/applets/"

code="TicTacToe.class"
width=120
height=120> </applet>
thecodebaseattribute specifies a path name on your
system for the local applet, whereas
thecodeattribute specifies the name of the bytecode file that contains the applet's code. The path
specified in thecodebaseattribute is relative to the
folder containing the HTML document that references
the applet.
Prepared by Harsha Chauhan

12

Difference between Applet & Application


Applet

Application

Small Program

Large Program

Used to run a program on


client Browser

Can be executed on stand


alone computer system

Applet is portable and can be


executed by any JAVA
supported browser.

Need JDK, JRE, JVM installed on


client machine.

Applet applications are


executed in a Restricted
Environment

Application can access all the


resources of the computer

Applets are created by


extending the
java.applet.Applet

Applications are created by


writing public static void
main(String[] s) method.

Applet application has 5


methods which will be
Application has a single start
automatically invoked on
point which is main method
Prepared by Harsha Chauhan
13
occurance of specific event

Difference between Applet & Application


Applet

contd

Application

Example:
importjava.awt.*;
importjava.applet.*;
public class MyClass
public
{
classMyclassextends
public static void
Applet
main(String args[])
{ publicvoidinit(){ }
{
publicvoidstart(){ }
}
publicvoidstop(){}
}
publicvoiddestroy()
{}
Prepared by Harsha Chauhan
publicvoidpaint(Grap

14

Life cycle of Java Applet


Various states, an applet, undergoes between its
object creation and object removal (when the job
is over) is known aslife cycle. Each state is
represented by a method. There exists 5 states
represented by 5 methods. That is, in its life of
execution, the applet exists (lives) in one of
these 5 states.
These methods are known as "callback
methods" as they are called automatically by
the browser whenever required for the smooth
execution of the applet. Programmer just write
the methods with some code but never calls.
Prepared by Harsha Chauhan

15

Life cycle of Java Applet


contd..
Following are the methods.
init() method
start() method
paint() method
stop() method
destroy() method
These methods are known aslife cycle methods.
These methods are defined
injava.applet.Appletclass
exceptpaint()method. The paint() method is
defined injava.awt.Componentclass, an indirect
super class of Applet.
Prepared by Harsha Chauhan

16

Life cycle of Java Applet


contd..
Browser Responsibilities
The life cycle methods are called ascallback
methodsas they are called implicitly by the browser
for the smooth execution of the applet. Browser should
provide an environment known ascontainerfor the
execution of the applet. Following are the
responsibilities of the browser.
It should call the callback methods at appropriate
times for the smooth execution of the applet.
It is responsible to maintain the life cycle of the applet.
It should have the capability to communicate between
applets, applet to JavaScript and HTML, applet to
browser etc.

Prepared by Harsha Chauhan

17

Life cycle of Java Applet


contd..
Description of Life Cycle methods
Even though, the methods are called
automatically by the browser, the
programmer should know well when
they are called and what he can do
with the methods.
Following is the schematic
representation of the methods.

Prepared by Harsha Chauhan

18

Life cycle of Java Applet

contd..

Description of Life Cycle methods


Even though, the methods are called
automatically by the browser, the
programmer should know well when
they are called and what he can do
with the methods. Following is the
schematic representation of the
methods.
Prepared by Harsha Chauhan

19

Life cycle of Java Applet


contd..

Prepared by Harsha Chauhan

20

Brief Description of Life Cycle Methods


Following is the brief description of the above methods.

init():
The applet's voyage starts here. In this
method, the applet object is created by the
browser. Because this method is called before
all the other methods, programmer can utilize
this method to instantiate objects, initialize
variables, setting background and foreground
colors in GUI etc.; the place of a constructor in
an application. It is equivalent toborn state
of a thread.
Prepared by Harsha Chauhan

21

Brief Description of Life Cycle Methods


stop:This method is automatically called
when the user moves off the page on
which the applet sits. It can, therefore, be
called repeatedly in the same applet.
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.
Prepared by Harsha Chauhan

22

Brief Description of Life Cycle Methods


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..

Prepared by Harsha Chauhan

23

Brief Description of Life Cycle Methods


A "Hello, World" Applet:
The following is a simple applet named
HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{ public void paint (Graphics g)
{ g.drawString ("Hello World", 25, 50);
}
}
Prepared by Harsha Chauhan

24

Brief Description of Life Cycle Methods


These import statements bring the
classes into the scope of our applet
class:
java.applet.Applet.
java.awt.Graphics.
Without those import statements, the
Java compiler would not recognize the
classes Applet and Graphics, which the
applet class refers to.
Prepared by Harsha Chauhan

25

How to run an Applet?


There are two ways to run an applet
By html file.
By appletViewer tool (for testing
purpose).

Prepared by Harsha Chauhan

26

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.

//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextendsApplet{

publicvoidpaint(Graphicsg){
g.drawString("welcome",150,150);
}
}
Prepared by Harsha Chauhan

27

Simple example of Applet by html file:


myapplet.html
<html>
<body>
<appletcode="First.class"width="300"
height="300">
</applet>
</body>
</html>

Prepared by Harsha Chauhan

28

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.
Prepared by Harsha Chauhan

29

Simple example of Applet by appletviewer


tool:

To execute the applet by


appletviewer tool, write in command
prompt:
c:\>javac First.java
c:\>appletviewer First.java

Prepared by Harsha Chauhan

30

How to run Java Applets in DOS


Create directory of your choice from within
the command window.
For example: >cd \Temp
Createsome Java source code with Notepad
from within the command window.
For example, suppose we want a class
named "A",
then we would start Notepad with the
name of the Java file:
>notepad A.java
Prepared by Harsha Chauhan

31

The source code,A.java, might look like this:


// This program draws a tall rectangle via the A.html
applet tag.
// mlc
// 9/1999
import java.applet.*;
import java.awt.*;
public class A extends Applet
{
private int w, h;
public void init( )
{ w = 45; h = 50; }
public void paint(Graphics g)
{ g.drawRect(w, h, 20, 80); } }
Don't forget to save the file!
Prepared by Harsha Chauhan

32

The source code,A.java, might look like this:


// This program draws a tall rectangle via the A.html
applet tag.
// mlc
// 9/1999
import java.applet.*;
import java.awt.*;
public class A extends Applet
{
private int w, h;
public void init( )
{ w = 45; h = 50; }
public void paint(Graphics g)
{ g.drawRect(w, h, 20, 80); } }
****Don't forget to save the file!
Prepared by Harsha Chauhan

33

Now, since this is an applet, we'll need to make an


HTML file.
We could call itA.htmland create it from the command
line using Notepad again:
>notepad A.html
TheA.htmlfile might look like this:
<html>
<p> This file launches the 'A' applet: A.class! </p>
<applet code="A.class" height=200 width=320> No
Java?!
</applet>
</html>
Again, be sure to save the file

Prepared by Harsha Chauhan

34

Applet methods
public void init ()
public void start ()
public void stop ()
public void destroy ()
public void paint (Graphics)
Also:
public void repaint()
public void update (Graphics)
public void showStatus(String)
public String getParameter(String)
Prepared by Harsha Chauhan

35

Why an applet works


You write an applet by extending the class Applet
Applet defines methods init( ), start( ), stop( ),
paint(Graphics), destroy( )
These methods do nothing--they are stubs
You make the applet do something by overriding
these methods
When you create an applet in BlueJ, it
automatically creates sample versions of these
methods for you
Prepared by Harsha Chauhan

36

public void init ( )


This is the first method to execute
It is an ideal place to initialize
variables
It is the best place to define the GUI
Components (buttons, text fields,
scrollbars, etc.), lay them out, and
add listeners to them
Almost every applet you ever write
will have an init( ) method
Prepared by Harsha Chauhan

37

public void start ( )


Not always needed
Called after init( )
Called each time the page is loaded and
restarted
Used mostly in conjunction with stop( )
start() and stop( ) are used when the
Applet is doing time-consuming
calculations that you dont want to
continue when the page is not in front
Prepared by Harsha Chauhan

38

public void stop( )


Not always needed
Called when the browser leaves the
page
Called just before destroy( )
Use stop( ) if the applet is doing
heavy computation that you dont
want to continue when the browser is
on some other page
Used mostly in conjunction with
start()
Prepared by Harsha Chauhan

39

public void destroy( )


Seldom needed
Called after stop( )
Use to explicitly release system
resources (like threads)
System resources are usually
released automatically

Prepared by Harsha Chauhan

40

Methods are called in this order


init and destroy are only
init()
called once each
start and stop are called
start()
whenever the browser
enters and leaves the page
do some work do some work is code
called by your listeners
stop()
paint is called when the
applet needs to be
destroy()
repainted
Prepared by Harsha Chauhan

41

public void paint(Graphics g)


Needed if you do any drawing or painting
other than just using standard GUI
Components
Any painting you want to do should be done
here, or in a method you call from here
Painting that you do in other methods may
or may not happen
Never call paint(Graphics), call repaint( )
Prepared by Harsha Chauhan

42

repaint( )
Call repaint( ) when you have
changed something and want your
changes to show up on the screen
repaint( ) is a request--it might not
happen
When you call repaint( ), Java
schedules a call to update(Graphics g)
Prepared by Harsha Chauhan

43

update( )
When you call repaint( ), Java
schedules a call to update(Graphics g)
Here's what update does:
public void update(Graphics g) {
// Fills applet with background color,
then
paint(g);
}

Prepared by Harsha Chauhan

44

Sample Graphics methods


A Graphics is something you can
paint on
Hello
g.drawString(Hello, 20, 20);
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
g.setColor(Color.red);
Prepared by Harsha Chauhan

45

Commonly used methods of Graphics class:


1) public abstract void drawString(String str,
int x, int y):is to draw used 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.
Prepared
by Harsha
Chauhan
46
5) public abstract
void
fillOval(int
x, int y, int

Commonly used methods of Graphics class: contd

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.
Prepared by Harsha Chauhan
47

Example of Graphics in applet:


importjava.applet.Applet;
importjava.awt.*;

publicclassGraphicsDemoextendsApplet{

publicvoidpaint(Graphicsg){
g.setColor(Color.red);
g.drawString("Welcome",50,50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
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);
}}
Prepared by Harsha Chauhan

48

myapplet.html
<html>
<body>
<appletcode="GraphicsDemo.
class"width="300"height="30
0">
</applet>
</body>
</html>
Prepared by Harsha Chauhan

49

Parameter in Applet
We can get any information from the
HTML file as a parameter. For this
purpose, Applet class provides a
method named getParameter().
Syntax:
publicStringgetParameter(Stringparam
eterName)

Prepared by Harsha Chauhan

50

Example of using parameter


in Applet
importjava.applet.Applet;
importjava.awt.Graphics;

publicclassUseParamextendsApplet
{

publicvoidpaint(Graphicsg){
Stringstr=getParameter("msg");
g.drawString(str,50,50);
}
}

Prepared by Harsha Chauhan

51

myapplet.html
<html>
<body>
<appletcode="UseParam.class"width=
"300"height="300">
<paramname="msg"value="Welcome
toapplet">
</applet>
</body>
</html>

Prepared by Harsha Chauhan

52

User Interfaces Components


Pre-Made UI Components
The Abstract Window Toolkit (AWT) supplies the
following UI components (the class that implements
each component is listed in parentheses):
Buttons (java.awt.Button)
Checkboxes (java.awt.Checkbox)
Single-line text fields (java.awt.TextField)
Larger text display and editing areas
(java.awt.TextArea)
Labels (java.awt.Label)
Lists (java.awt.List)
Pop-up lists of choices (java.awt.Choice)
Sliders and scrollbars (java.awt.Scrollbar)
Drawing areas (java.awt.Canvas)
Menus (java.awt.Menu, java.awt.MenuItem,
java.awt.CheckboxMenuItem)
Prepared by Harsha Chauhan
53

Methods for Using UI Components


in Applets
Because the Applet class inherits from the
AWT Container class, it's easy to add
components to applets and to use layout
managers to control the components'
onscreen positions.
Here are some of the Container methods an
applet can use:
setLayout: Sets the layout manager. Types
of layouts include FlowLayout and
BorderLayout.
add :Adds thePrepared
specified
Component.
by Harsha Chauhan
54

Thank you

Prepared by Harsha Chauhan

55

Das könnte Ihnen auch gefallen