5.Java Applets and Graphics Programming
5.Java Applets and Graphics Programming
Concepts Applications are stand alone Applets are small java programs
programs that can be run that are designed to be included
independently without need of web in a HTML web document.They
browsers. require a Java enabled browser
for execution.
Access Java application hava full access to Applet have no disk and network
local file system and network access.
Main Method They require main()method for They does not require
execution. main()method for execution.
Execution Application can run programs from Applets can not run programs on
the local system. local machine.
Init() Born
start()
Stop()
destroy()
Running Idle Dead
start()
paint()
1.Init()
java.awt.Component
java.awt.Container
java.awt.panel
java.applet.Applet
--All the applets extensions of the java.applet.Applet class.
--The built in base Applet class offers methods which a derived user defined
Applet class may invoke to avail information and services from the
browser context.
--Applet class provides 4 life cycle methods of applet;
1.public void init
2.public void start()
3.public void stop()
4.public void destroy()
--These methods can do the following tasks:
• Can retrieve applet parameters.
• Can retrieve the location of HTML file in the network which contains the
applet.
• Can retrieve the location of the applet class directory in the network.
• Can display status message on the browser window.
• Can fetch an image.
• Can fetch an audio clip.
• Can change the size of the applet.
--Also the applets class give an interface through which
the viewer or browser is able to get the information
regarding the applet and controls the execution of the
applet.
--The Applet class provides default implementations of
all the applet regarding methods.
--User can override those methods as per requirement.
--Applet class can have constructor,but usually no need
of it as we do not create object of Applet class.
Appletviewer Tool
--AppletViewer is a standalone command-line program
provided by Sun MicroSystems to run Java applets.
--Applets can be executed using web browsers such as
Mozilla,Google Chrome or using Appletviewer tool.
--Appletviwer is generally used by developers for
testing their applets before deploying them to a
website.
--Even through the applet viewer operates on HTML
documents,but there is requirnment of embedded
applet tags;any other HTML code in the document is
ignored.
--Each time the applet viewer encounters an applet tag in an
HTML document ,it launches a separate applet viewer window
containing the respective applet.
--only drawback of using applet viewer is that it will not show an
Applet will run within the real web setting.
--Because the applet viwer ignores all HTML except applet
tags,it does not even attempt to display other information
contained in the HTML document.
--To run appletviewer tool we have to use the Native Abstract
Window Toolkit(NAWT) and use the sun applet.AppletViewer
class.
Syntax::
AppletViewer programmename.java
Embedding <applet>tag in java code
Example 1 .we will create a simple applet running messages.
import java.applet.*;
import java.awt.*;
/*
<applet code="appletEx1" width=200 height=200>
</applet>
*/
public class appletEx1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to MyFirst Applet",20,50);
g.drawString("Welcome to Applet Window",20,80);
}
}
--Now to run the applet,first we have to compile it same as application
Javac Programme.java
--To execute applet we will use AppletViewer tool as follows
AppletViewer Programname.java
Explanation
--Here we have imported two packages:
applet:Contains Applet class.
awt: (Abstract Window Toolkit)—contains Graphics class.
--In the comment section we have given<applet>tag.It is considered by yhe compiler
and not ignored.
--This tag contains 3 attributes:Code is name of class file,width and height sets the
size of applet window.
--next appletEx1 is our user defined class which we have extended from Applet class.
--Then we have used paint()method which takes Graphics object as parameter.
--g.drawString()-This methods takes three Parameters;message to print and x,y
coordinates for message location.Here the origin is at top left cornor of the applet
window.
Setting Background and foreground color of
an applet
import java.applet.*;
import java.awt.*;
/*
<applet code="appletEx3" width=200 height=200>
</applet>
*/
public class appletEx3 extends Applet
{
public void init()
{
setBackground(Color.red);
setForeground(Color.blue);
}
public void paint(Graphics g)
{
g.drawString("Welcome to MyApplet",40,25);
}
}
Applet Tag,Adding Applet to HTML File
--The APPLET tag of HTML is used to start an applet
either from a web browser or an applet viewer.
--The HTML tag allows a Java applet to be embedded in
an HTML document.
--A number of optional attribute can be used to control
an applet’s appearance,for example,the dimensions of
the applet panel.
--Also parameter can be independently defined which
can be passed to the applet to control its behaviour.
Structure Of Applet Tag
<applet code=“appletEx” -or-[object=“serializedapplet”]
Width=“pixel” height=“pixcel”[codebase=“codebaseURL”]
[archive=“archiveList”]
[alt=“alternateText”]
[name=“appletInstanceName”]
[align=“alignment”]
[vspace=“pixcel”]
[hspace=“pixcel”]
>
[<param name=“appletAttribute1” value=“value”>]
[<param name=“appletAttribute2” value=“value”>]
………
………
[alternateHTML]
<applet>
Attributes in applet tag
--The attribute code,width and height are mandatory and all other attributes are
optional,which are shown in brackets([]).
--The attributes need not follow the order that was specified in the above syntax.
Attributes in Applet
1.Codebase
2.Code
3.Width
4.Height
5.Archive
6.Alt
7.Name
8.Align
9.Vspace
10.Hspace
11.Param
12.alternateHTML
1.Codebase
--This refer to base URL of the applet.That is the URL directory that contains the
applet class file.
--If this attribute is not specified then the HTML document’s URL directory is
taken as the CODEBASE.
2.Code
--It is the name of Java applet.
--It is a class file which contains the compiled applet code.
--The extension in file name is optional.
3.Width
--This refer to the width of the applet panel specified in pixcel in the browser
window.
4.Height
--This refer to the height of the applet panel specified in pixcel in the browser
window.
--The width and height specify the applet’s display area.
--This applet area does not include any windows or dialogue boxes that the
applet shows.
5.Archive
--There are one or more archieve files containing java classes and
other resources that will be needed to load applet.
6.Alt
--This refers to text to be displayed if the browser understands
the applet tag but cannot run java applet’s.
7.Name
--This refers to a name for the applet instance(object)which
makes it possible for applets to communicate with each other
on the same HTML page.
8.Align
--This refer to the alignment of the applet, The possible attribute
values are
LEFT,RIGHT,TOP,BOTTOM,MIDDLE,BASELINE,
TEXTTOP,ABSMIDDLE and ABSBOTTOM.
9.Vspace
--This refer to space,specified in a number of pixcel,used as margin above
and below the applet.
10.Hspace
-- --This refer to space,specified in a number of pixcel,used as margin left
and Right the applet.
11.Param
--The param tag,specifies an applet parameter as a name-value pair.
--The name is the parameter’s name value its value.
--The value of these parameter can be obtained using the
getParameter()method.
12.alternateHTML
--This is ordinary HTML to be displayed in the absence of java or if the
browser does not understand the applet tag.
--This is different from the alt attribute which understand the applet tag but
cannot run ,whereas the alternateHTML,tag is provided when a browser
does not support applet.
Passing Parameter to Applet
--In java we can pass user defined parameters to an applet through the
<PARAM>tag.
--The <PARAM>tag has two attributes name and value.
--The value of <PARAM>tag can be retrived with the help of
getParameter()method by providing name of <PARAM>tag as
argument.
--The Syntax of <PARAM> tag is
<APPLET>
<PARAMNAME=parameter1_name
VALUE=parameter1_value>
<PARAMNAME=parameter2_name
VALUE=parameter2_value>
<PARAMNAME=parametern_name
VALUE=parametern_value>
</APPLET>
import java.applet.*;
import java.awt.*;
/*
<applet code="appletParameterEx1" width=200 height=100>
<param name="pid" value="111"/ >
<param name="pname" value="Kunal"/>
</applet>
*/
public class appletParameterEx1 extends Applet
{
int id;
String name,msg;
public void init()
{
id=Integer.parseInt(getParameter("pid"));
name=getParameter("pname");
}
public void paint(Graphics g)
{
msg=id +"" +name;
g.drawString(msg,20,30);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletParameterEx2" width=200 height=100>
<param name="pid" value="111"/ >
<param name="pname" value="Kunal"/>
</applet>
*/
public class appletParameterEx2 extends Applet
{
int id;
String name,msg;
public void init()
{
name=getParameter("pname");
}
public void paint(Graphics g)
{
msg="Hello" + name;
g.drawString(msg,20,30);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletParameterEx3" width=200 height=100>
<param name="str1" value="Hi"/ b>
<param name="str2" value="Kunal"/>
</applet>
*/
public class appletParameterEx3 extends Applet
{
String s1,s2,msg;
public void init()
{
s1=getParameter("str1");
s2=getParameter("str2");
}
public void paint(Graphics g)
{
msg=s1+s2;
showStatus(msg);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletParameterEx4" width=200 height=100>
<param name="username" value="kunal"/ >
</applet>
*/
public class appletParameterEx4 extends Applet
{
String user;
public void init()
{
user=getParameter("username");
}
public void paint(Graphics g)
{
int noc=user.length();
g.drawString("Numbers of Characters are:"+noc,20,30);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletParameterEx5" width=200 height=100>
<param name="accno" value="110"/ >
<param name="balance" value="1000"/ >
</applet>
*/
public class appletParameterEx5 extends Applet
{
int ac,bal;
public void init()
{
ac=Integer.parseInt(getParameter("accno"));
bal=Integer.parseInt(getParameter("balance"));
}
public void paint(Graphics g)
{
if(bal<500)
g.drawString("Low balance",30,50);
else
g.drawString("Sufficient balance",30,50);
}
}
Adding Controls to Applets
--we can add different controls such as Labels,Push buttonsCheck boxes,Choice
lists,Lists,Scroll bars,Text Area,Text Field on the Applet.
--To add control on applet java provides following methods:
add(control);
Example
import java.applet.*;
import java.awt.*;
/*
<applet code="appletControlEx1" width=200 height=100>
<param name="accno" value="110"/ >
<param name="balance" value="1000"/ >
</applet>
*/
public class appletControlEx1 extends Applet
{
TextField t1;
Button b1;
public void init()
{
t1=new TextField(20);
b1=new Button("Click");
setBackground(Color.magenta);
add(t1);
add(b1);
}
}
Graphics Programming
--Graphics is one of the most important feature of Java.
--Java applets can be written to draw lines,arcs,figures,images and text in
different fonts and styles.
--Different colors can be incorporated in display.
Graphics Classs
--The graphics class defines a number of drawing methods,each shape can be
drawn edge only or field.
--To draw shapes on the screen ,we can call one of the methods available in
the graphics class.
--To draw shape ,we only need to use the appropriate method with the required
arguments.
--The most commonly used drawing methods included in the graphics class
are Listed Below:
Method Description
clearRect() Erase the rectangular area of the canvas.
copyArea() Copies the Rectangular area of the canvas
to another area.
drawArc() Draws a hollow arc
drawLine() Draws a Straight line
drawOval() Draws a hollow Oval
drawPolygon() Draws a hollow Polygon
Methods Description
drawRect() Draws a hollow Rectangle
drawRoundRect() Draws a hollow rectangle with rounded corners.
drawString() Display a text String
FillArc() Draws a filled Arc.
fillOval() Draws a filled Oval
fillPolygon() Draws a filled Polygon
fillRect() Draw a filled Rectangle
fillRoundRect() Draw a filled rectangle with rounded corners.
1.Lines
--Lines are drawn by means of the drawLine() method.
Syntax
Void drawLine(int startX,int StartY,int endX,int endY);
--drawLine() displays a Line in the current drawing color that begins at(start
X,start Y)and ends at (end X,end Y).
import java.applet.*;
import java.awt.*;
/*
<applet code="appletLine" width=300 height=100>
</applet>
*/
public class appletLine extends Applet
{
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
g.setColor(Color.cyan);
g.fillRect(50,50,100,100);
g.setColor(Color.green);
g.drawRoundRect(100,100,150,150,50,50);
g.setColor(Color.magenta);
g.fillRoundRect(150,150,200,200,15,15);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletRectangle2" width=400 height=300>
</applet>
*/
public class appletRectangle2 extends Applet
{
g.setColor(Color.red);
g.fillRect(50,50,200,200);
g.setColor(Color.blue);
g.drawString("Hello Second Year Students",80,160);
}
}
3.Ellipse,Circle
--To draw an ellipse,use drawOval(),to fill an ellipse,use fillOval().
--These methods are shown here:
Syntax:
void drawOval(int top,int left,int width,int height)
void fillOval(int top,int left,int width,int height)
--Both the methods are used to draw ellipse as well as circle.
--Top and left are for the left top cornor of imaginary rectangle,and width and
height sets its size.
--Means an imaginary rectangle will be drawn centers of which will be joined
to form ellipse or circle.
--if width and height for bounding rectangle are provided equal,then it will
draw circle.
import java.applet.*;
import java.awt.*;
/*
<applet code="appletEllipseCircle" width=300 height=200>
</applet>
*/
public class appletEllipseCircle extends Applet
{
g.setColor(Color.red);
g.drawOval(10,75,50,50);
g.setColor(Color.blue);
g.fillOval(100,75,75,50);
}
}
4.Arcs
--Arcs can be drawn drawArc() and fillArc() as shown here:
Syntax:
void drawArc(int top,int left,int width,int height,int startAngle,int
sweepAngle);
void fillArc(int top,int left,int width,int height,int startAngle,int
sweepAngle);
--The arc is bounded by the rectangle whose upper-left cornor is specified by
top,left and whose width and height are specified by width and height.
--The arc is drawn from startAngle through the angular distance specified by
seepAngle.Angles are specified in degrees.
--zero degree is on the horizontal,at the three o’clock position.
--The arc is drawn counterclockwise if swwepAngle is positive,and clockwise
if sweepAngle is negative.
--Therefore ,to draw an arc from twleve o’clock to six o’clock,the start angle
would be 90 and the swwepAngle would be 180.
import java.applet.*;
import java.awt.*;
/*
<applet code="appletArc" width=300 height=200>
</applet>
*/
public class appletArc extends Applet
{
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,40,70,70,0,75);
g.drawArc(10,100,70,80,0,175);
g.fillArc(100,100,70,90,0,270);
g.drawArc(200,80,80,80,0,180);
}
}
5.Polygon
--It is possible to draw arbitrarily shaped figures using
drawPolygon() and fillPolygon(),shown here:
Syntax:
void drawPolygon(int x[],int y[],int numPoints);
Void fillPolygon(int x[],int y[],numPoints);
--The polygon’s endpoints are specified by the coordinate pairs
contained within the x and y arrays.
--There are alternative forms of these methods in which the
polygon is specified by polygon object.
import java.applet.*;
import java.awt.*;
/*
<applet code="appletPolygon" width=230 height=210>
</applet>
*/
public class appletPolygon extends Applet
{
/*
<applet code="appletcolorEx1" width=250 height=300>
</applet>
*/
public class appletcolorEx1 extends Applet
{
public void init()
{
setBackground(Color.pink);
setForeground(Color.blue);
}
public void paint(Graphics g)
{
g.drawString("Welcome to my applet:",40,25);
}
}
import java.applet.*;
import java.awt.*;
/*
<applet code="appletcolor" width=250 height=300>
</applet>
*/
public class appletcolor extends Applet
{
}
}
Font Class
--The font class states fonts,which are used to render text in a
visible way.
A)Variables Defined by Font class:Name,pointSize,size,style
--Following are the important fields defined by font class:
1.protected String name:
--The logical name of the font,as passed to the constructor.
2.Protected float pointSize:
--The point size of the font in font.
3.Protected int size:
--The point size of the font,rounded to integer.
4.Protected int style:
--The style of the Font,as passed to the constructor.
B)Font Methods:
--getFamily(),getFont(),getFontName(),getSize(),
getStyle()
--Following are the important methods of Font class:
public String getFamily()
--Returns the family name of the Font.
--The family name of a font is font specific.Two fonts such as
Helvetica Bold have the same family name,Helvitica,whereas
their font face names are Helvitica Bold and Helvitica Italic.
public static Font getFont(String nm)
--Returns a font object from the system properties list.
--nm is treated as the name of a system property to be obtained.
public String getFontName()
--Returns the font face name of this Font.
--For example,Helvitica Bold could be returned as a font face name.
--Use getFamily to get the family name of the font.
--Use getName to get logical name of the font.
public int getSize()
--Returns the point size of this font,rounded to an integer.
public int getStyle()
--Returns the style of this font.The style can be PLAIN,BOLD,ITALIC,or
BOLD+ITALIC.
public abstract void setFont(Font font)
--set this graphics context’s font to the specified font.
--all subsequent text operations using this graphics context use this font.
--A null argument is silently ignored.
import java.applet.*;
import java.awt.*;
/*
<applet code="appletFont" width=230 height=210>
</applet>
*/
public class appletFont extends Applet
{
int fsize;
String fname;
Font f;
public void init()
{
fsize=15;
fname="Arial";
f=new Font(fname,Font.BOLD,fsize);
setBackground(Color.cyan);
}
public void paint(Graphics g)
{
g.drawString("Welcome to my Applet",10,50);
g.setFont(f);
g.drawString("Hello Friends",50,150);
}
}
C.getAllFonts(),getAvailableFontFamilyNames(),
Of the Graphics Environment Class
1.public abstract Font[]getAllFonts()
--Returns an array containing one-point size instance of all fonts
available in this GraphicsEnvironment.
2.public abstract String[] getAvailableFontFamilyNames()
--Returns an array containing the names of all font families in
this GraphicsEnvironment lacalized for default locale,as
returned by locale.getDefault().
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
/*
<applet code="ListJavaFonts" width=230 height=210>
</applet>
*/
public class ListJavaFonts extends Applet
{
public void paint(Graphics g)
{
GraphicsEnvironment graphicsEnvironment=GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[]=graphicsEnvironment.getAvailableFontFamilyNames();
int y=20;
for(int i=0;i<fontNames.length;i++)
{
g.drawString(fontNames[i],10,y);
y+=20;
}
}
}