You are on page 1of 63

Lecture -10

Applet programming

1
Lecture Summary
• In this lecture, I will introduce you to the
techniques necessary to develop applet.
– Learning Applet basic concepts: Local and remote
applets
– How applet differ from application;
– Creating your own applet, applet tags, parameters,…
– Graphical methods, drawString, drawRect…
– Containers and components, like textbox, Labels,
CkeckBoxes used to develop applet….

• Style: Mixture of lecture and lab


2
Introduction to Applet
• In the previous sections, we have been dealing with
classes that contain a main method and run as a
standalone application.
• Java code can also be executed under the control of
a web browser.
• Code written to execute under the control of a web
browser is called an applet.
• Applets can be used to provide dynamic user-
interfaces and a variety of graphical effects for web
pages.
3
Introduction to Applet…

• Applets are small java programs that are embedded in web


pages.
• Applets can be transported over the internet from one
computer(web server) to another (client computers).

• The current uses of applets include the following:


• Animated graphics
• Video games
• Image map that respond to mouse movement
• Advanced text display
• Database reports
4
Local and remote applet
• We can embed applets into web pages in two ways.
1. We can write our own applet and embed them into web
page.
2. We can download an applet from a remote computer and
then embed into a web page.

• An applet developed locally and stored in a local


system is known as Local applet.
• When a web page tries to find a local applet, it doesn’t
need to use the internet and therefore the local system
does not require the network connection.
• It simply reaches the directories in the local system
and locates and loads the specified applet.
5
Local applet

Browser

Local Applet

6
Remote Applet

• A remote applet is the applet, which is


developed by someone else and stored on a
remote computer connected to the internet.

• If the system is connected to the internet, we


can download the remote applet onto our
system via internet and run it.

7
Remote applet

Remote applet Internet


downloaded to Remote applet
local…

Local remote
computer(client) computer(server)

8
Remote applet…
• 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) .
• It must be specified in the applet’s HTML document
as the value of codebase attribute.

• Note: In the case of local applet, codebase may be


absent or can specify a local directory.

9
How applet differ from application
• Although both applet and standalone application
are java programs, there are significant difference
between them.
– Applets as previously described, are the small programs
while applications are larger programs.
– Applets don’t have the main() method while in an
application execution starts with the main method.

10
How applet differ from application…

• Applets can run in our browser’s window or in an


appletviewer.
• To run the applet in an appletviewer will be an
advantage for debugging.
• Java applets are the best way of creating the
programs in java.

• Applets are just designed for handling the client side


problems.
• While the java applications are designed to work
with the client as well as server.
11
Applet vs. Program Structure

• Assuming a graphical program (swing), the


corresponding applet has:
– a web page, not a command line,
– a public Applet subclass, not a JFrame,
– an init(), not a constructor,
– a start(), not a main(),
– a destroy(), not a setDefaultCloseOperation(),

12
Applet vs. Program Attributes

• Assuming a graphical program (swing), the


corresponding applet has:
– height and width attributes, not setSize(),
– the <title></title> tag, not setTitle(),
– start() and stop(), not setVisible().

• Also, these are under control of the browser, not


the applet, which can only react.

13
Applet HTML
• An applet is embedded in a standard HTML file using the
applet tag.
<html>
<head>
<title>page-title </title>
</head>
<body bgcolor=black text=white link=blue>
<applet code = "sa.class" height = 0
width = 0>
</applet>
</body>
</html>
– Applet tags should appear in the body of an HTML
document. 14

Applet Tag Attributes
• There are twelve attributes specific to the applet
tag.
• The three important ones are:
– code: a URL to an applet class.
– height and width: the applet real-estate height and
width in pixels (required).

<applet code = "sa.class" height = 10


width = 20> </applet>

15
LAB: Creating applet
• To create an applet, we have to use a class called
Applet, which is available inside the package
java.applet.

• The Applet class must be the supper class of all


applets that are embedded on a web page.

• An "applet" is an object which runs under the


control of a suitable environment
– usually a browser, JDK applet viewer.
16
LAB: Creating applet…
• Let us now create an applet which display a message:
“ Welcome to the applet world!”
Steps:
1. Write the applet code that will be displayed on the web
browser.

//importing the Applet class


import java.applet.Applet;
//importing the Graphics class
import java.awt.*;
//creating subclass of Applet class
public class AppletExample extends Applet {
17
LAB: Creating applet…
//paint method to display text on applet

public void paint(Graphics g) {


g.drawString(“Welcome to the applet
world!”,50,50);
}
}

2. Save the file with the name AppletExample.java and


compile it with the same manner as u were doing in
application programming as shown below:
c:\java>javac AppletExample.java 18
LAB: Creating applet…
3. Create the HTML file that will call the applet. Save the file
as AppletExample.html
The contents are:
<html>
<body>
<applet code=“AppletExample.class” width=300
height=300>
</applet>
</body>
</html>

• In the above code, <applet> tag has been used.

19
LAB: Creating applet…
• This assumes that the file AppletExample.class is located
in the same directory with the HTML document.
• If this is not the case, you can use another modifier,
CODEBASE, to give the URL of the directory that contains
the class file.
• The value of CODE itself is always just a file name, not a
URL.
• The code attribute of this tag indicates the class name
AppletExample and

• The attribute width and height indicate the width and


height of the applet, respectively.
20
LAB: Creating applet…
• To display the greeting, we must override the paint method of
java.awt.

• The paint method deals with the display of graphics on our


applet - we'll override it to show our message.

• Run the applet either:


• By double clicking on web browser or
• by using the appletviewer on command prompt.

Using applet viewer:


c:\java>javac AppletExample.java
c:\java>AppletViewer AppletExample.html
21
Applet tag
 The <applet> tag is used to embed an applet within an
HTML page.
 We have already seen three required attributes of applet
tag: code, width and height.
 The following is a list of other applet tags attribute:
• Codebase: the location where the browser can find the
byte code for the applet.
– It represents a URL (relative to where the HTML document is
located).
• Name: The name of this instance of the applet.
• You can create multiple applets on a web page and they
can locate each other by using this name attribute and the
appletContext class.
22
Applet tag…
 In addition to these attributes, an <applet> tag can also
contain any number of parameters, which are defined
using the <param> tag.
 The <param> tag is nested within the <applet> tag and
has two attributes:
• Name and
• Value
 The syntax for using <param> is:
<applet>
<param name=“param-name” value=“param-value”>
<param name=“param-name” value=“param-value”>

</applet>

23
Applet tag…
• An applet can obtain the parameters using the following
applet methods;
public String getParameter(String paramname)
Returns the value of the given parameter.
• If the specified paramName does not occur in any param
tag, then getParameter returns the value null.
• Parameter allow the writer of an applet to customize the
applet based on input from the writer of the HTML page.

• Example: the following HTML document,


AppletParam.html, displays an applet named Hello World
and SansSerif.
24
LAB: Illustrating Applet parameters
<html>
<head>
<title> Testing Applet parameters</title>
</head>
<body>
<applet code="AppletParam.class" width=200
height=300>
<param name="message" value="Hello World">
<param name="font" value="SansSerif">
</applet>
</body>
</html>
25
Illustrating Applet parameters cont’d…
import java.applet.Applet;
import java.awt.*;

public class AppletParam extends Applet {


String display;
String fontName;
public void init()
{
String value;
value=getParameter("message");
if(value==null)
value="Hello World"; 26
else
display=value;
value=getParameter("font");
if(value==null)
value="SansSerif";
else
fontName=value;
}
public void paint(Graphics g)
{
g.drawString(display,50,50);
g.drawString(fontName,100,100);
}
}
27
Graphics methods in Applet
• To draw String on the screen on the specified
column and row position.
method : drawString()
Syntax : drawString(String s, int column,int
row)

• To draw line we start from one coordinate(x,y) and


end with (x1,y1) coordinate.
• Method: drawLine()
• Syntax: drawLine(int x,int y,int x1,int y1)

28
Graphics methods …
• To draw hollow Rectangle of the specified width and height
starting from a particular x and y position.
method: drawRect()
syntax: drawRect(int x,int y,int width,int height)

• To draw solid rectangle of the specified width and height


starting from a particular x and y position.
method : fillRect()
syntax: fillRect(int x,int y,int width,int height)

29
Graphics methods cont’d…

• To draw circle or ellipse we use the following


methods:
• Method : drawOval()
• Syntax: drawOval(int x,int y,int height,int width)

• To fill solid circle or ellipse use the following method

• Method: fillOval()
• Syntax: fillOval(int x,int y,int width,int
height)
30
LAB: Illustrating Graphics methods
import java.applet.*;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Graphics demonstration",50,50);

g.setColor(Color.blue);
g.drawRect(100,100,100,100);
g.fillRect(150,200,200,200);
g.setColor(Color.yellow);
g.drawOval(80,100,90,90);
g.fillOval(200,300,300,200);
}
} 31
GUI (Containers and Components)
• There are two elements of GUI: container and
component.
• Container is for displaying components.
• Components must be displayed with in container.
• A button is an example of a component.
• Whereas a frame is an example of a container.
– To display a Button, you place it within a frame and display
the frame.
• Component is an abstract class that is the parent class of
the various GUI components of AWT:
– Button, CheckBox, Choise, Label, List…
• Containers is an abstract class that is the parent class of
the containers of AWT:
– Window, Panel.
32
Adding Components to a Container

 A Component is added to a Container using add()


method.
• Button:
is a rectangular button that can be pushed by clicking
it with a mouse.
• Constructors:
– public Button();
– Public Button(String label);
• Methods
– Public void setLabel(String label);
– Public String getLabel();
33
Adding Components to a Container…
• Checkbox
It is a toggel box that can be selected, marked with a check
mark or unselected.
• Constructors:
– Public Checkbox();
– Public Checkbox(String label);
– Public Checkbox(String label,CheckboxGroup
g,boolean state);
• Methods:
– Public String getLabel();
– Public void setLabel(String label);
– Public boolean getState();
– Public void setState(boolean state);

34
Adding Components to a Container…

• Checkbox Group:
it creates a set of mutually execlusive check boxes in
which one and only one check box can be checked at
any one time.
• Constructors:
– Public checkboxGroup();

• Methods:
– Public String getSelectedCheckbox();
– Public void setSelectedCheckbox(Checkbox box);

35
Adding Components to a Container…
• Choice:
is a pop-up list of strings from which a single string can
be selected.
• Constructors:
– Public choice();
• Methods:
– Public void addItem(String item);
– Public String getItem(int index);
– Public int getSelectedIndex();
– Public String getSelectedItem();
– Public int getItemCount();
– Public void select(String str);
36
Adding Components to a Container…
• Label:
is a string of text that displayed on the container.
• Label cannot generate any event.
• Constructors:
– Public Label();
– Public Label(String label);
– Public Label(String label,int
alignment);
• Methods:
– Public void setText(String text);
– Public String getText();
37
Adding Components to a Container…
• TextField:
it creates a single-line text entry area, where user
can enter strings, modifies an existing string etc…
• Constructors:
– Public TextField();
– Public TextField(String text);

• Methods:
– Public String getText();
– Public void setText();
– Public void setEditable(boolean t);

38
LAB: Illustrating GUI in Applet
import java.applet.Applet;
import java.awt.*;
public class Controls extends Applet{
public void init()
{
Button b=new Button("Ok");
add(b);
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("Java",cbg,true);
Checkbox cb2=new Checkbox("C++",cbg,false);
add(cb1);
add(cb2);
39
List l=new List();
l.add("CS");
l.add("IT");
l.add("EE");
l.add("CE");
add(l);
Label lb=new Label("Controls test");
add(lb);
TextField tf=new TextField(" Here we go");
add(tf);
}
}
//HTML CODE
<applet code=“Controls” width=300 height=400>
<applet>
40
Capturing an event
• You’ll notice that if you compile and run the applet above,
nothing happens when you press the buttons.
• This is where you must step in and write some code to
determine what will happen.

• action( ) has two arguments:


– the first is of type Event and contains all the information
about the event that triggered this call to action( ).

• For example,
– it could be a mouse click,
– a normal keyboard press or release,
– a special key press or release, the fact that the component got or
lost the focus,
– mouse movements, or drags, etc.
41
Capturing an event…
• The second argument is usually the target of the event,
which you’ll often ignore.
• The second argument is also encapsulated in the Event
object so it is redundant as an argument.

• When you place controls on a form, some types of controls


(buttons, check boxes, drop-down lists, menus) have a
“standard action” that occurs, which causes the call to
action( ) with the appropriate Event object.

– For example, with a button the action( ) method is called


when the button is pressed and at no other time.

42
Capturing an event…

• Action method
public boolean action(Event event, Object o)
{
repaint();
return true;
}

43
LAB: Calculator programming using Applet

import java.applet.Applet;
import java.awt.*;

public class Calculator extends Applet {


CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1;
Checkbox cb2;
Checkbox cb3;
Checkbox cb4;
Label a1;
Label a2;
Label a3;
TextField t1;
TextField t2;
TextField t3;
44
LAB: Calculator programming using Applet

public void init() {


setLayout(null);
setBackground(Color.red);
cb1=new Checkbox("Addition",cbg,false);
cb2=new Checkbox("Subtraction",cbg,false);
cb3=new Checkbox("Multiplication",cbg,false);
cb4=new Checkbox("Division",cbg,false);
a1=new Label("1st num");
a2=new Label("2nd num");
a3=new Label("Result");
t1=new TextField();
t2=new TextField();
t3=new TextField();
cb1.setBounds(210,300,100,70);
cb2.setBounds(320,300,100,70);
cb3.setBounds(430,300,100,70);
cb4.setBounds(540,300,100,70);
45
LAB: Calculator programming using Applet

a1.setBounds(100,100,100,30);
a2.setBounds(100,160,100,30);
a3.setBounds(100,220,100,30);
t1.setBounds(210,100,100,30);
t2.setBounds(210,160,100,30);
t3.setBounds(210,220,100,30);
add(cb1);
add(cb2);
add(cb3);
add(cb4);
add(a1);
add(a2);
add(a3);
add(t1);
add(t2);
add(t3); } 46
LAB: Calculator programming using Applet

public void paint(Graphics g)


{
g.drawString("Enter the numbers",50,50);
double a=Double.parseDouble(t1.getText());
double b=Double.parseDouble(t2.getText());
double c=0.0;
if(cb1.getState())
c=a+b;
else if(cb2.getState())
c=a-b;
else if(cb3.getState())
c=a*b;
else
c=a/b;
String s=String.valueOf(c);
t3.setText(s); } 47
LAB: Calculator programming using Applet

public boolean action(Event event, Object


o)
{
repaint();
return true;
}
}

48
Applet Life cycle
• Applet runs in the browser and its lifecycle method
are called by JVM at its birth, its death and when it is
momentarily away.

• As shown in the figure, every applet can be said to


be in any of the following state:
– New Born state
– Running state
– Idle state
– Dead state

49
Life cycle of an applet
Init()

New
born
state

start() stop()

Run Idle
state state
start()

destroy()
paint()

Dead
state

50
Applet Life cycle…
• When a user views a web page that contains an applet,
the following sequence of events occurs regarding the
life cycle of the applet:
1. The web browser downloads the necessary byte code from
the web server where the code is located.(this web server is
referred to as the code base).
2. The browser creates an instance of the Applet class, invoking
the default constructor.
3. The applet is displayed in the web page, with the location
and size of the applet determined by the HTML.
4. The browser invokes the init() method on the applet.
5. The browser invokes the start() method on the applet.

51
Applet Life cycle…

6. The browser invokes the paint() method on the applet.

7. The applet is now live and running within the web page.

8. The browser calls paint() whenever the applet needs to


repaint itself.

9. The browser invokes the stop() method when the user


leaves the web page or the applet is about to be destroyed.

10. The browser invokes the destroy() method just before


destroying the applet.

52
New Born state
• The life cycle of an applet is begin on that time when the
applet is first loaded into the browser and called the init()
method.
• The init() method is called only one time in the lifecycle of
an applet.
• The init() method is basically called to read the PARAM
tag in the html file.
• The init() method retrieve the passed parameter thru the
PARAM tag of html file using getParameter() method.
• All the initialization such as initialization of variables and
the objects like image, sound file are loaded in the init()
method.
• After the initialization of the init() method user can
interact with the applet.
53
New Born state…

Syntax for init() method

public void init()


{
//statements
}

54
Running state
• After initialization , this state will automatically occur by
invoking the start() method of applet class which again
calls the paint() method.
• The running state also occurs from idle state when the
applet is reloaded.

• This method may be called multiple times when the applet


needs to be started or restarted.
• For example;
– If the user wants to return to the applet, in this situation the start()
method of an applet will be called by the web browser and the user
will be back on the applet.
• In the start() method user can interact with in the applet.

55
Running state…

Syntax for start() method

public void start()


{
//statements
}

56
Idle state
• 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.

• The stop() method can be called multiple times in the life


cycle of an applet or should be called at least one time.

• For example;
– The stop() method is called by the web browser on that time when
the user leaves one applet to go to another applet.

57
Idle state…

Syntax for stop() method

public void stop()


{
//statements
}

58
Dead state
• When the applet programs terminate, the destroy()
method is invoked which makes an applet to be in
dead state.
• The destroy() method is called only one time in the
life cycle of applet like init() method.

Syntax
public void destroy()
{
// statements
}
59
Display state
• The applet is said to be in display state when the
paint() method is called.
• This method can be used when we want to display
output in the screen.
• This method can be called any number of times.
• paint() method is must in all applets when we want to
draw something on the applet window.
• paint() method takes Graphics object as argument.
Syntax
public void paint(Graphics g) {
//statements
}
60
LAB: Program to illustrate the sequence of method call when an applet is
loaded.

import java.applet.*;
import java.awt.*;
public class AppLife extends Applet{
String msg=“the currently executing method”;
public void init()
{
msg+=“init()”;
}
public void start()
{
msg+=“start()”;
}

61
Program to illustrate the sequence of method call when an applet is loaded
cont’d…

public void stop()


{
msg+=“stop()”;
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

/*<applet code=“AppLife.class” width=“200”


height=“200”> </applet>*/

62
Summary
• An applet is a Java program that runs in a web
browser.
• An applet is written by extending the
java.applet.Applet class.

• When an applet is instantiated in a browser, the


browser communicates with the applet by invoking the
init(), start(), stop(), paint() and destroy() methods.
• The appletviewer tool that comes with the SDK is
useful for the development of applets.
63

You might also like