You are on page 1of 13

Unit – IV

JAvA Applets And GrAphics ProgrAmming


08 Hours
10 Marks

5.1.1 Applet
Applet is a small java program which is primarily used for Internet
computing. It can be easily transported from one computer to another computer on
Internet.
Java applet is not full-featured application program. Usually it perform
small tasks. It can perform various operations like
- Arithmetic operations
- Display graphics
- Play sound
- Create animations
- Accept user input
- Play interactive games

Java applet does not have main( ) method. It can run using either Applet
Viewer or java-enabled web browsers. As applet runs through web pages, they
help a lot in creating dynamic web pages.

5.1.2 Applet Life Cycle


Applet, in its lifetime goes through various states as shown in figure 5.1.

Begin Born/
(Load Applet) Initialization

start( )
stop( )
Idle/
Display Running
Stopped
paint( ) start( )
destroy( )

Dead

Figure 5.1: Applet Life Cycle


Born/ Initialization state
When applet is loaded by calling init( ) method of applet class, it enters
Born/ Initialization state.

Running state
Whenever start( ) method of applet class is called, applet enters in Running
state. The start( ) method gets called automatically after init( ) method. Ever a
stopped applet may also call start( ) method.

Idle/ Stopped state


When user leaves page containing currently running applet, the applet
enters in Idle/ Stopped state. Applet also enters in this state on calling stop( )
method.

Dead state
Applet is said to be in Dead state, when it is removed from memory. This
state occurs only once in the lifetime of an applet. Applet enters this state when
destroy( ) method gets invoked automatically on quitting the browser.

Display state
Whenever applet performs output operations, it moves to Display state.
This state is not assumed to be part of applet life cycle.

5.1.3 Developing and Testing Applet


Steps involved in developing and testing applet are as follows.
1. Write Applet code (Create .java file).
2. Compile it (to get .class file).
3. Design webpage using HTML tags (Create .html file). The webpage
should contain <APPLET> tag mentioning source file of applet code.
4. Test the applet code with the help of java-enabled web browser or
appletviewer.

Step 1: Writing Applet code


While writing applet code we have to use two main classes Applet and
Graphics. For using Applet class we have to import
import java.applet.*;
For using Graphics class we have to import Abstract Windowing
Toolkit(awt) as follows.
Import java.awt.*;
We have to extend the Applet class to our own applet class. Output of
applet code is displayed by paint( ) method. Therefore we must override paint( )
method in our Applet class. The paint( ) method requires Graphics object reference
as its argument.
public void paint(Graphics g)
{
---
}
A sample applet code (which should be saved as .java file) is shown below.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to Applet Programming”,5,20);
//This method displays the mentioned text at 5(left), 20(top)
//pixel location in the browser or appletviewer
}
}

Step 2: Compiling Applet code


The above applet code (.java file) must be compiled to get a .class file.

Step 3: Designing Webpage


A webpage may be designed with the help of various HTML tags. Some
important HTML tags are mentioned below.

Tag Usage
<HTML> … </HTML> HTML code must be written within this tag.
<! ……> Comment may be written in this tag.
<HEAD> … </HEAD> It includes Head section within it. It includes
information about the webpage.
<BODY> … </BODY> It includes Body section within it. This is the actual
body of HTML code of the webpage.
<TITLE> … </TITLE> Title of the webpage may ne mentioned here. It must
be used within <HEAD> tag.
<P> … </P> For displaying a paragraph of text.
<BR> Inserts a single line break
<B> … </B> For making text Bold
<I> … </I> For making text Italic
<U> … </U> For making text Underlined

The most important tag that must be included in the webpage here is
<APPLET> tag. This tag is used for embedding java applet in HTML document.
Some important attributes supported by APPLET tag are discussed below.

Attribute Usage
Code It is used to link Java applet to this HTML document. Here
we must mention name of classfile of the applet code.
width Determines width of applet in pixels.
height Determines height of applet in pixels.
align Specifies alignment of applet (Possible values are: left, right,
top, bottom, middle, baseline).
codebase Specifies relative base URL for the applet.
hspace Specifies horizontal spacing around applet.
Vspace Specifies vertical spacing around applet.
name Defines name of the applet

A sample webpage or HTML document is shown below.


<HTML>
<HEAD>
<! My first webpage with applet>
<TITLE>This is my First Applet</TITLE>
</HEAD>
<BODY>
<APPLET code=”MyApplet.class” width=”300” height=”300”>
</APPLET>
</BODY>
</HTML>

Step 4: Testing the applet


Applet can be tested either by using java-enabled web browser or by using
appletviewer. For running the applet using web browser, we have to simply open
the html file in the web browser. For running applet using appletviewer, we have
to pass the html file as attribute to appletviewer command as,
prompt> appletviewer htmlfilename
When run with appletviewer, output of only applet is shown and all other
html code is ignored.

5.1.4 Passing parameters to applet


We can pass user-defined parameters to the applet using <PARAM> tag
within <APPLET> tag. Multiple parameters may be passed to applets. The syntax
for <PARAM> tag is as follows.
<PARAM name=”parametername” value=”parametervalue”>
The applet code may receive the value of parameter passed with the help of
getParameter( )method. As there may be multiple parameters, while calling
getParameter( ) method, we have to specify parametername as argument of this
method. All the parameter values are assumed to be of String type always.
An example applet code and corresponding html file is shown below.

//MyApplet01.java
import java.applet.*;
import java.awt.*;
public class MyApplet01 extends Applet
{
public void paint(Graphics g)
{
String p;
p=getParameter("P1");
g.drawString(p,100,100);
p=getParameter("P2");
g.drawString(p,100,150);
}
}

Webpage named Applet01.html


<HTML>
<HEAD>
<TITLE>This is my Second Applet</TITLE>
</HEAD>
<BODY>
<APPLET code="MyApplet01" width="300" height="300">
<PARAM name="P1" value="India">
<PARAM name=”P2” value=”Maharashtra”>
</APPLET>
</BODY>
</HTML>

Output:

5.1.5 Adding different controls to applet


We may add different controls to applet like label, text-field, button etc. For
achieving this we have to import jawa.awt.* in our applet code.

Label Control:
Label control is used for simply displaying text on the applet window. This
control may be added in our applet by creating object of Label class. Object may
be created in two ways.
Label l1 = new Label(“Enter Username:”);
//simple constructor. Its displays the specified text in the label

Label l2 = new Label(“Enter Password”,Label.LEFT);


//Alignment argument may contain values as Label.LEFT, Label.RIGHT or
Label.CENTER

After creating the label object, the control is added to applet by passing the
created object to add method as follows,
add(l1);
add(l2);

TextField Control:
TextField control is used for getting input from user of applet. This control
may be added in our applet by creating object of TextField class. Object may be
created as follows.
TextField t1 = new TextField(15);
//sets size of textfield to 15

After creating the textfield object, the control is added to applet by passing
the created object to add method as follows,
add(t1);
For setting value of textfield at runtime, setText( ) method may be used by
passing the text to be displayed as its argument as shown below.
t1.setText(“Hello”);
or
t1.setText(str);

Also, we may get the value of the textfield by using getText( ) method as
shown below.
String s1;
s1 = t1.getText( );

Button Control:
Button control is used for performing some specified action on clicking the
button. This control may be added in our applet by creating object of Button class.
Object may be created as follows.
Button b1 = new Button(“Submit”);
//sets caption of button to Submit

After creating the Button object, the control is added to applet by passing the
created object to add method as follows,
add(b1);

For handling events of Button, we should add actionListener for this button
as shown below.
b1.addActionListener(this);

For this, our applet class must implement ActionListener interface. Events of
the button may be handled by implementing actionPerformed( ) method as below.
public void actionPerformed(ActionEvent e)
{
String str = new String(“Button is clicked”);
if(e.getSource( ) == b1)
{
t1.setText(str);
}
}

Example:
// Applet getting inputs from user and performing addition and subtraction
import java.awt.*;
import java.graphics.*;

class MyApplet02 extends Applet implements ActionListener


{
Label l1, l2, l3;
TextField t1, t2, t3;
Button b1, b2;
public void init( )
{
l1 = new Label(“First Number: ”);
t1 = new TextField(10);
l2 = new Label(“Second Number: ”);
t1 = new TextField(10);
l3 = new Label(“Result: ”);
t3 = new TextField(10);
b1 = new Button(“Add”);
b2 = new Button(“Subtract”);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int a, b, c;
if(e.getSource( ) == b1) //perform addition
{
x = Integer.parseInt(t1.getText( ));
y = Integer.parseInt(t2.getText( ));
z = x + y;
t3.setText(String.valueOf(z));
}
if(e.getSource( ) == b2) //perform subtraction
{
x = Integer.parseInt(t1.getText( ));
y = Integer.parseInt(t2.getText( ));
z = x - y;
t3.setText(String.valueOf(z));
}
}
}

5.2 Graphics Programming


For performing Graphics programming we have to use various classes as
follows.
- Graphics class
- Color class
- Font class
- GraphicsEnvironment class

5.2.2 Graphics class


Graphics class includes various methods for drawing different shapes. Some
of the methods are discussed here.

Lines
Line can be drawn by calling drawLine( ) method by any Graphics object. The
syntax for the same is as follows,
g.drawLine(int x1, int y1, int x2, int y2);
// It draws a line from point (x1,y1) to point (x2,y2)
Rectangles
A rectangle may be drawn with the help of drawRect( ) method. The syntax of the
method is shown below.
g.drawRect(int left, int top, int width, int height);
//g is graphics object
//(left,top) is starting point of rectangle
//rectangle of specified width and height is drawn
Similarly, a filled rectangle may be drawn with the help of fillRect( ) method. The
syntax of the method is shown below.
g.fillRect(int left, int top, int width, int height);

(left, top)

height

width

Circles & Ellipses


For drawing an ellipse drawOval( ) method is used. The syntax of the method is
shown below.
g.drawOval(int left, int top, int width, int height);
//g is graphics object
//(left,top) is starting point of rectangle defining the oval
//Oval of specified width and height is drawn
Similarly, a filled ellipse may be drawn with the help of fillOval( ) method. The
syntax of the method is shown below.
g.fillOval(int left, int top, int width, int height);

(left, top)

height

width

If same value is mentioned for width and height in the drawOval( ) method and
fillOval( )methos, these methods draw circles.

Arcs
For drawing an arc drawArc( ) method is used. The syntax of the method is
shown below.
g.drawArc(int left, int top, int width, int height, int startingangle, int
sweepangle);
//g is graphics object
//(left,top) is starting point of rectangle defining the arc
//width and height are specified for arc
//startingangle tells the angle from which drawing of arc should be started
//sweepangle tells for how much angle the arc is to be swept (or drawn)

(left, top)

height
Starting angle
width

Sweep angle

Similarly, a filled arc may be drawn with the help of fillArc( ) method. The syntax
of the method is shown below.
g.fillArc(int left, int top, int width, int height, int startingangle, int sweepangle);

Polygons
Polygons may be drawn with various ways.

With the help of multiple drawLine( ) calls


As polygon is a closed diagram with multiple lines connecting multiple vertices of
polygon, we can draw a polygon with multiple lines as shown below.
Code Output
(10,10)

g.drawLine(10,10,70,50);
g.drawLine(70,50,50,50);
g.drawLine(50,50,10,30); (10,30)
g.drawLine(10,30,10,10);

(50,50) (70,50)

With the help of drawPolygon( ) method


The syntax of drawPolygon( ) method is as follows.
g.drawPolygon(xArray, yArray, no_of_points);
Here xArray and yArray are arrays containing x coordinates and y coordinates of
the vertices of polygon, where first vertex and last vertex must be same. The
argument no_of_points tells number of vertices in the arrays xArray and yArray.
Example is shown below.
Code Output
(10,10)

int x[ ] = {10,70,50,10,10};
int y[ ] = {10,50,50,30,10};
g.drawPolygon(x,y,5); (10,30)

(50,50) (70,50)
Similarly, we can draw a filled polygon with fillPolygon( ) method as,
g.fillPolygon(xArray,yArray,no_of_points);

We may pass an object of Polygon class to methods drawPolygon( ) as well as


fillPolygon( ). The object of Polygon class is created as follows.
Polygon p = new Polygon(x, y, n);
Here x is xArray and y is yArray as discussed above. Also n is number of
elements in x or y array. Example code is shown below.
Code Output
(10,10)

int x[ ] = {10,70,50,10,10};
int y[ ] = {10,50,50,30,10};
Polygon p = new Polygon(x,y,x.length); (10,30)
g.drawPolygon(p);

(50,50) (70,50)
Even more simply we may create a Polygon object with default constructor (i.e.
without any arguments) and then add vertices to the object with the help of
addPoint() method. An example code is shown below.
Code Output
(10,10)
Polygon p = new Polygon(x,y,x.length);
p.addPoint(10,10);
p.addPoint(70,50);
p.addPoint(50,50); (10,30)
p.addPoint(10,30);
p.addPoint(10,10);
g.drawPolygon(p);
(50,50) (70,50)

5.2.3. Color class


Color class includes various constants as,
Color.black Color.blue Color.cyan Color.darkgray Color.gray
Color.green Color.lightgray Color.magenta
Color.orange
Color.pink Color.red Color.white Color.yellow etc.
Various methods of Graphics class which handles colours are as follows.
setColor( ) method is used for setting drawing colour. Example of its usage is
shown below.
g.setColor(Color.red);
g.fillRect(100,100,200,150);
//This code draws a filled rectangle with red colour.
getColor( ) method is used for retrieving current drawing colour of Graphics
object. Its usage is shown below.
Color c = g.getColor( );
String s = c.toString( );
g.drawString(s,100,100);
//It gets the drawing color and displays it.
There are two more methods which can be used without Graphics object.
They are setForeground( ) method and setBackground( ) method which are used for
setting foreground colour (text is written with this colour) and for setting
background colour respectively. Usage is shown below.
setForeground(Color.magenta);
setBackground(Color.yellow);

5.2.4. Font class


Abstract Windowing Toolkit has a Font class which supports various fonts.
This class supports specifying and using fonts. Font class contains various fields
(variables) as,
String fontName – Name of Font
int fontStyle – Style of Font.
Supported values are Font.PLAIN, Font.BOLD, Font.ITALIC
Multiple values may be combined with | as shown below.
Font.BOLD | Font.ITALIC
int fontSize – Size of Font
float pointsize – Size of Font in points

Various methods supported by Font class are as follows.

getFamily( ) method
The syntax of this method is as follows,
String getFamily( )
It returns name of Font Family to which the invoking font belongs to.

getFontName( ) method
The syntax of this method is as follows,
String Font getFont(String property)
It returns Font associated with specified system property.

getSize( ) method
The syntax of this method is as follows,
int getSize( )
It returns size (in points) of the invoking Font.

getStyle( ) method
The syntax of this method is as follows,
int getStyle( )
It returns style of the invoking Font.

getFont( ) method
This method is used with Graphics object which returns Font object currently
used by the Graphics object. This is method is called as follows,
Font f = g.getFont( );

setFont( ) method
This method is used for setting current Font of Graphics object. One example
of usage of this method is shown below.
Font f = new Font(“Dialog”, Font.ITALIC, 14);
g.setFont(f);

Example applet code using above methods is shown below.

import java.awt.*;
import java.applet.*;
class MyApplet03 extends Applet
{
Font f1;
public void init( )
{
f1 = new Font(“Arial”,Font.BOLD,16);
}
public void paint(Graphics g)
{
g.setFont(f1);
g.drawString(“Welcome”,100,50);
Font f2 = g.getFont( );
String family = f2.getFamily( );
String fontname = f2.getFontName( );
int size = f2.getFontSize( );
int style = f2.getFontStyle( );
String msg = “Family = ”+family+“ Font Name = ”+fontname;
msg = msg+“ Size = ”+size+“ Style = ”+style;
g.drawString(msg,50,50);
}
}

5.2.5. GraphicsEnvironment class


Abstract Windowing Toolkit supports a GraphicsEnvironment class which is
accessible by local operating system. This class supports various methods as
follows.

getAvailableFontFamilyNames( ) method
This method returns a String array containing names of all available Font
families.

getAllFonts( ) method
This method returns array of fonts objects for all available fonts.

getLocalGraphicsEnvironment( ) method
This is a static method which returns current graphics environment.

Example applet code using above methods is shown below.

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

class MyApplet04 extends Applet


{
public void paint(Graphics g)
{
GraphicsEnvironment
ge=GraphicsEnvironment.getLocalGraphicsEnvironment( );
String[ ] familyList = ge.getAvailableFontFamilyNames( );
int i;
for(i=0;i<familyList.length;i++)
{
g.drawString(familyList[i],50,50*(i+1));
}
Font[ ] fontList = ge.getAllFonts( );
for(i=0;i<fontList.length;i++)
{
g.drawString(fontList[i].getFontName( ),100,100*(i+1));
}
}

Sample Questions:
1. Differentiate between Java Applet and Java Application (any four points).
[4M]
2. Explain life cycle of applet. [4M]
3. Describe Applet life cycle with diagram. [4M]
4. Describe Applet life cycle in detail. [6M]
5. Give syntax of <param> tag to pass parameters to applet. [2M]
6. Explain how to pass parameters to an applet. Write an applet to accept
username in the form of parameter and print “Hello <username>”. [6M]
7. Design an applet to pass username and password as parameters and
check if password contains more than 8 characters. [6M]
8. Write syntax and usage of following methods. [2M]
i) paint( ) ii) getParameter( )
9. Describe use of following methods. [4M]
i) drawOval( ) ii) getFont( ) iii) drawRect( ) iv) getFamily( )
10. Give usage of following methods. [4M]
ii) drawOval( ) ii) getFont( ) iii) drawArc( ) iv) getFamily( )
11. Write syntax and example of [4M]
i) drawRect( ) ii) drawOval( )
12. Write a program to design an applet showing three concentric circles filled
with three different colours. [4M}

You might also like