CH-5 Java_notes.
CH-5 Java_notes.
Applet
Advantages of applet
It provides GUI, facilitates graphics animation and multimedia.
Avoids risk and provide 2 way interactions between webpages.
Applets can work on all versions of Java plugin.
disadvantages of applet
Java applets requires JVM so first time it takes significant startup time.
It is difficult to design and build good user interface in applet as compare to
html technology.
Some organization only allowed software installed by administrator, As a
result many users cannot view applet by default.
Types of Applets
1. Local Applets
Page 1
A local applet is specified by a path name and a file name.
2. Remote Applet
For e.g.
<applet
codebase="http://www.vpt.edu.in/applets/"
code="JPR.class"
width=120
Page 2
height=120>
Applet Application
Applet does not use main() method Application use main() method for
for initiating execution of code initiating execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to Application can read from or write
files in local computer to files in local computer
Applet cannot communicate with Application can communicate with
other servers on network other servers on network
Applet cannot run any program Application can run any program
from local computer. from local computer.
Applet are restricted from using Application are not restricted from
libraries from other language such using libraries from other language
as C or C++
Applets are event driven. Applications are control driven.
Page 3
Life Cycle of Applet
Page 4
Applet Life Cycle: An Applet has a life cycle, which describes how it
starts, how it operates and how it ends. The life cycle consists of four
methods:
1. init()
2. start()
3. stop()
4. destroy().
1. Initialization State (The init() method):
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 life cycle on an Applet.
The init() method is basically called to read the “PARAM” tag in the html
file.
The init () method retrieve the passed parameter through the “PARAM”
tag of html file using get Parameter() 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 and mostly applet contains the init() method.
Syntax:
public void init()
{
----
----
}
Page 5
Syntax:- public void start()
{
……..
……..
}
3. Idle (The Stop() method):
An applet becomes idle when it is stopped from running. The stop() method
stops the applet and makes it invisible.
Stopping occurs automatically when we leave the page containing the
currently running applet. We can also do so by calling the stop() method
explicitly.
The stop() method can be called multiple times in the life cycle of applet
like the start () method 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 another applet and the start()
method is called on that time when the user wants to go back into the first
program or Applet.
Syntax:- public void stop()
{
……..
……..
}
4. Dead State (The destroy() method):
The destroy() method is called to terminate an Applet. an Applet is said to
be dead when it is removed from memory.
This occurs automatically by invoking the destroy() method when we quit
the browser. It is useful for clean-up actions, such as releasing memory
after the applet is removed, killing off threads and closing
network/database connections.
Thus this method releases all the resources that were initialized during an
applet’s initialization.
Syntax:-public void destroy()
{
……..
Page 6
……..
}
method used whenever we want to call update method along with the call to
paint method; call to update method clears the current window, performs an
Syntax:
package <packagename>;
Page 7
The above syntax shows how a repaint method is used in java. The repaint
Therefore repaint method can be directly called from a class extending Applet or
its subclasses.
directly called from the Applet class’s subclasses. The repaint method is
responsible for handling update to the paint cycle of the applet. Whenever we
want a component to repaint itself, we need to call the repaint method. In case
we have made changes to the appearance of a component but have not made
any changes to its size, then we can call the repaint method to update the new
the graphical user interface, which communicates to the graphical user interface
to perform some action at a future instance of time. The whole idea behind the
Example:
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code=repaint_java.class width=300 height=300></applet>*/
public class repaint_java extends Applet {
int i;
public void paint(Graphics g)
{
g.drawString("i = "+i, 100, 100);
try{
Page 8
Thread.sleep(1000);
}catch(InterruptedException ex){}
i++;
repaint();
}
}
Program:
/*<applet code= WelcomeJava width= 300 height=300>
</applet>*/
import java. applet.*;
import java.awt.*;
public class WelcomeJava extends Applet
{
public void paint( Graphics g)
{
g.drawString(“Welcome to java”,25,50);
}
}
Applet Skeleton
Page 9
1.1.1 An Applet Skeleton
When user close that applet window, then output is like this:
Page 11
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the
body
section of HTML file.
2. Specify the name of the applet’s .class file.
3. If the .class file is not in the current directory then use the codebase
parameter to
specify:-
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is
on
a remote computer.
4. Specify the space required for display of the applet in terms of width and
height in
pixels.
5. Add any user-defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non-java browser is used.
7. Close the applet declaration with the </APPLET> tag.
Open notepad and type the following source code and save it into file name
“Hellojava.java”
import java.awt.*;
import java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello Java",10,100);
}
}
Page 12
After compilation “Hellojava.class” file will be created. Executable applet is
nothing but the .class file of the applet, which is obtained by compiling the source
code of the applet. If any error message is received, then check the errors,
correct them and compile the applet again.
Page 13
</BODY>
</HTML>
1 Example:
param.java
import java.applet.*;
import java.awt.*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = " Welcome to Java applet ";
str = "Hello " + str;
}
public void paint(Graphics g)
{
g.drawString(str, 200, 200);
}
}
param.html
<html>
<applet code=param.class height=300 width=300>
<param Name="pname" value="Welcome to Java applet">
</applet>
</html>
2 Example:
Page 14
User need to write java source code.
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str; public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
User need to write html code now
<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
Page 15
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]>
[< PARAM NAME = AttributeNameVALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
Page 16
Java graphics class includes methods for drawing many different types of
shapes, from simple line to polygon to text in variety of form.
Graphics is class present in java.awt package in which is used to perform
all the graphical operation in applet window.
There are different methods available in graph class which are explain as
follows:
___________________________________________________________________
1. Display Text:-
drawString() method is used to display the string in an applet window
Syntax: void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example: g.drawString(“WELCOME”, 10, 10);
2. drawOval( )
Drawing Ellipses and circles: To draw an Ellipses or circles used drawOval()
method can be used.
Syntax: void drawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is
specified by top and left and whose width and height are specified by width
and height to draw a circle or filled circle, specify the same width and
height the following program draws several ellipses and circle.
Example: g.drawOval(10,10,50,50);
To draw filled oval use the method g.fillOval(30,140,70,40)
3. drawPolygon()
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], int numPoints)
The polygon‟s end points are specified by the co-ordinates pairs contained
within the x and y arrays. The number of points define by x and y is
specified by numPoints.
Example:
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
Page 17
To draw filled polygon fillPolygon() is used.
4. drawArc( )
It is used to draw arc.
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int
sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle
is starting angle of arc sweep_angle is degree around the arc
Example: g.drawArc(10, 10, 30, 40, 40, 90);
5. drawRect()
The drawRect() method display an outlined rectangle.
Syntax: void drawRect(int top,int left,int width,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of
the Rectangle is specified by width and height.
Example: g.drawRect(10,10,60,50);
To draw filled rectangle fillRect() is used.
6. drawLine()
The drawLine() method is used to draw line which take two pair of
coordinates, (x1,y1) and (x2,y2) as arguments and draws a line between
them. The graphics object g is passed to paint() method.
Syntax: g.drawLine(x1,y1,x2,y2);
Example: g.drawLine(100,100,300,300;)
7. drawRoundRect()
This methods draws rounded rectangle, it takes 6 parameters first 4 is sane
as drawRect()and last are x diameter and y diameter.
Syntax:- g.drawRoundRect(int x, int y, int width, int height, int Xdiameter,
int ydiameter);
Example: g.drawRoundRect(30,140,70,40,10,10)
To draw filled rounded rectangle use the method
g.fillRoundrect(30,140,70,40,10,10)
8. Setting Color:
Used to set color for graphics.
Syntax: g.setColor(Color.red);
9. Creating font object and Setting font
Syntax:- Font(String FontName, String FontStyle, int FontSize)
Page 18
Example:-a=(“Times New Romen”, Font.BOLD+Font.ITALIC, 14)
Font Class
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
Methods Description
String getFamily( ) Returns the name of the font family to
which the invoking font belongs.
static Font getFont(String Returns the font associated with the system
property) property specified by property. null is
returned if property does not exist.
String getFontName() Returns the face name of the invoking font.
String getName( ) Returns the logical name of the invoking
font.
int getSize( ) Returns the size, in points, of the invoking
font.
int getStyle( ) Returns the style values of the invoking
font.
int hashCode( ) Returns the hash code associated with the
invoking object.
boolean isBold( ) Returns true if the font includes the BOLD
style value. Otherwise, false is returned.
boolean isItalic( ) Returns true if the font includes the ITALIC
style value. Otherwise, false is returned.
boolean isPlain( ) Returns true if the font includes the PLAIN
style value. Otherwise, false is returned.
Example:
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
Page 19
Font f,f1;
String s,msg;
String fname;
String ffamily;
int size;
int style;
public void init()
{
f= new Font("times new roman",Font.ITALIC,20);
setFont(f);
msg="is interesting";
s="java programming";
fname=f.getFontName();
ffamily=f.getFamily();
size=f.getSize();
style=f.getStyle();
String f1=f.getName();
}
public void paint(Graphics g)
{
g.drawString("font name"+fname,60,44);
g.drawString("font family"+ffamily,60,77);
g.drawString("font size "+size,60,99);
g.drawString("fontstyle "+style,60,150);
g.drawString("fontname "+f1,60,190);
}
}
/*<applet code=Shapes.class height=300 width=300></applet>*/
Output:
Page 20
Q. Write a simple applet program which display tree concentric circle.
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.drawString("Concentric Circle",120,20);
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:
Page 21
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,60,40,30);
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
Page 22
g.fillOval(50,250,100,100);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:
import java.lang.*;
import java.awt.*;
import java.applet.*;
public class Hello extends Applet
{
String message;
public void init()
{
message=getParameter("username");
message="Hello" + message;
}
public void paint(Graphics g)
{
g.drawString(message, 100,100);
}
}
/*<applet code=Hello.class height=300 width=300>
Page 23
<param name="username" value="Abc">
</applet> */
Q. Design an applet which display a triangle filled with red colour and a
message as “The triangle” in blue below it.
import java.awt.*;
import java.applet.*;
public class DrawTriangle extends Applet
{
public void paint(Graphics g)
{
int xPoints[] = { 10, 170, 80, 10 };
int yPoints[] = { 20, 40, 140, 20 };
int nPoints = xPoints.length;
g.set Color(Color.red);
g.fillPolygon(xPoints, yPoints, nPoints);
g.setColor(Color.blue);
g.drawString("The triangle",50,160);
}
}
/* <applet code="DrawTriangle.class" width="350" height="300">
</applet> */
Output:
Page 24
Q. Write a program to draw a bar chart for plotting students passing
percentage in last 5 years.
Page 25
g.setColor(Color.red);
for(int i=0;i<n;i++)
{
g.drawString(label[i],100,100+i*50);
g.fillRect(150,80+i*50,values[i],40);
}
}
}
Code for html file
<html>
<applet code="barChart.class" height=700 width=700>
<param name="cols" value="4">
<param name="label1" value="2001">
<param name="label2" value="2002">
<param name="label3" value="2003">
<param name="label4" value="2004">
Page 26
public class shapes extends Applet
{
public void paint(Graphics g)
{
g.setFont(new Font("Arial",10, 12));
g.drawString("Types of Shapes",150,10);
g.drawLine(20,20,60,60);
g.drawRect(20,70,50,40);
g.setColor(Color.red);
g.fillOval(100,30,40,90);
g.fillRoundRect(30,140,70,40,10,10);
g.fillArc(100,130,90,50,190,190);
}
}
Page 27
import java.awt.*;
import java.applet.*;
public class backfore extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.yellow);
g.setColor(Color.red);
g.drawString("Demo of background and Foreground color",10,50);
}
}
/*<applet code="backfore.class" width=100 height=100>
</applet>
*/
Output:
import java.awt.*;
import java.applet.*;
public class CirSqr extends Applet
{
public void paint(Graphics g)
{
g.drawOval(70,30,100,100);
g.drawRect(90,50,60,60);
}
}
Page 28
/*<applet code="CirSqr.class" height=200 width=200>
</applet> */
Output:
Q. Write the applets to set background with red color and foreground
with blue color.
FontMetrics class
The FontMetrics class is used to return the specific parameters for a particular
Font object. An object of this class is created using the getFontMetrics() methods
supported by the Component class and other classes, such as the Graphics and
Page 29
Toolkit classes. The FontMetrics access methods provide access to the details of
the implementation of a Font object.
The bytesWidth(), charWidth(), charsWidth(), getWidth(), and stringWidth()
methods are used to determine the width of a text object in pixels. These
methods are essential for determining the horizontal position of text on the
screen.
notepad
Class GraphicsEnvironment
The GraphicsEnvironment class describes the collection
of GraphicsDevice objects and Font objects available to a Java application on a
particular platform.
Page 30
getAllFonts()
public abstract Font[] getAllFonts()
Returns an array containing a one-point size instance of all fonts available in
this GraphicsEnvironment. Typical usage would be to allow a user to select a
particular font. Then, the application can size the font and set various font
attributes by calling the deriveFont method on the chosen instance.
This method provides for the application the most precise control over
which Font instance is used to render text. If a font in
this GraphicsEnvironment has multiple programmable variations, only one
instance of that Font is returned in the array, and other variations must be
derived by the application.
If a font in this environment has multiple programmable variations, such as
Multiple-Master fonts, only one instance of that font is returned in the Font array.
The other variations must be derived by the application.
Returns:
Example:
import java.awt.GraphicsEnvironment;
Page 31
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
return;
}
}
Output:
Fonts available on this platform:
Agency FB
Algerian
Arial
Arial Black
Arial Narrow
Arial Rounded MT Bold
Bahnschrift
Baskerville Old Face
Bauhaus 93
Bell MT
Berlin Sans FB
Berlin Sans FB Demi
Bernard MT Condensed
Blackadder ITC
Bodoni MT
Bodoni MT Black
Bodoni MT Condensed
Bodoni MT Poster Compressed
Book Antiqua
Bookman Old Style
Bookshelf Symbol 7
Bradley Hand ITC
Britannic Bold
Broadway
Brush Script MT
Calibri
Page 32
Calibri Light
Californian FB
Calisto MT
Cambria
Cambria Math
Candara
Candara Light
Castellar
Centaur
Century
Century Gothic
Century Schoolbook
Chiller
Colonna MT
Comic Sans MS
Consolas
Constantia
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Corbel
Corbel Light
Courier New
Curlz MT
Dialog
DialogInput
Ebrima
Edwardian Script ITC
Elephant
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Page 33
Felix Titling
Footlight MT Light
Forte
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
Freestyle Script
French Script MT
Gabriola
Gadugi
Garamond
Georgia
Gigi
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Haettenschweiler
Harlow Solid Italic
Harrington
High Tower Text
HoloLens MDL2 Assets
Impact
Imprint MT Shadow
Informal Roman
Ink Free
Javanese Text
Page 34
Jokerman
Juice ITC
Kristen ITC
Kunstler Script
Leelawadee UI
Leelawadee UI Semilight
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Magneto
Maiandra GD
Malgun Gothic
Malgun Gothic Semilight
Marlett
Matura MT Script Capitals
Microsoft Himalaya
Microsoft JhengHei
Microsoft JhengHei Light
Microsoft JhengHei UI
Microsoft JhengHei UI Light
Microsoft New Tai Lue
Microsoft PhagsPa
Microsoft Sans Serif
Microsoft Tai Le
Microsoft YaHei
Microsoft YaHei Light
Microsoft YaHei UI
Microsoft YaHei UI Light
Microsoft Yi Baiti
Page 35
MingLiU-ExtB
MingLiU_HKSCS-ExtB
Mistral
Modern No. 20
Mongolian Baiti
Monospaced
Monotype Corsiva
MS Gothic
MS Outlook
MS PGothic
MS Reference Sans Serif
MS Reference Specialty
MS UI Gothic
MT Extra
MV Boli
Myanmar Text
Niagara Engraved
Niagara Solid
Nirmala UI
Nirmala UI Semilight
NSimSun
OCR A Extended
Old English Text MT
Onyx
Palace Script MT
Palatino Linotype
Papyrus
Parchment
Perpetua
Perpetua Titling MT
Playbill
PMingLiU-ExtB
Poor Richard
Pristina
Page 36
Rage Italic
Ravie
Rockwell
Rockwell Condensed
Rockwell Extra Bold
SansSerif
Script MT Bold
Segoe MDL2 Assets
Segoe Print
Segoe Script
Segoe UI
Segoe UI Black
Segoe UI Emoji
Segoe UI Historic
Segoe UI Light
Segoe UI Semibold
Segoe UI Semilight
Segoe UI Symbol
Serif
Showcard Gothic
SimSun
SimSun-ExtB
Sitka Banner
Sitka Display
Sitka Heading
Sitka Small
Sitka Subheading
Sitka Text
Snap ITC
Stencil
Sylfaen
Symbol
Tahoma
TeamViewer15
Page 37
Tempus Sans ITC
Times New Roman
Trebuchet MS
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Verdana
Viner Hand ITC
Vivaldi
Vladimir Script
Webdings
Wide Latin
Wingdings
Wingdings 2
Wingdings 3
Yu Gothic
Yu Gothic Light
Yu Gothic Medium
Yu Gothic UI
Yu Gothic UI Light
Yu Gothic UI Semibold
Yu Gothic UI Semilight
Page 38