Java Applets & Graphics Programming
Java Applets & Graphics Programming
Java Programming
As per MSBTE ‘I’ Scheme Syllabus
JPR-22412
Unit- V
Java Applets & Graphics Programming
Total Marks- 10
Contents:
5.1 Introduction to applets Applet, Applet life cycle (skeleton), Applet tag, Adding
Applet To HTML file, passing parameter to applet, embedding <applet>tags in java
code, adding controls to applets.
5.2 Graphics Programming Graphics classes, lines, rectangles, ellipse, circle, arcs,
polygons, color & fonts, setColor(), getColor(), setForeGround(), setBackGround(),
font class, variable defined by font class: name, pointSize, size, style, font methods:
getFamily(), getFont(), getFontname(), getSize(), getStyle(), getAllFonts() &
getavailablefontfamilyname() of the graphics environment class.
Applet Basics-
Basically, an applet is dynamic and interactive java program that inside the web
page or applets are small java programs that are primarily used in internet computing. The
java application programs run on command prompt using java interpreter whereas the
java applets can be transported over the internet form one computer to another and run
using the appletviewer or any web browser that supports java.
An applet is like application program which can perform arithmetic operations,
display graphics, play sounds accept user input, create animation and play interactive
games. To run an applet, it must be included in HTML tags for web page. Web browser is
a program to view web page.
Every applet is implemented by creating sub class of Applet class. Following
diagram shows the inheritance hierarchy of Applet class.
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Fig. Chain of classes inherited by Applet class in java
5.1.1 Differentiate between applet and application (4 points). [W-14, S-15, W-15 ]
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language
JPR-22412 Page 2
Unit-V- Java Applets & Graphics Programming
Applet enters the running state when the system calls the start() method of
Applet class. This occurs automatically after the applet is initialized. start() can also
be called if the applet is already in idle state. start() may be called more than once.
start() method may be overridden to create a thread to control the applet.
APPLET Tag:
The APPLET tag is used to start an applet from both an HTML document and
from an applet viewer.
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]>
[< PARAM NAME = AttributeName1 VALUE = AttributeValue>]
[<PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
JPR-22412 Page 4
Unit-V- Java Applets & Graphics Programming
</APPLET>
CODEBASE is an optional attribute that specifies the base URL of the applet code or
the directory that will be searched for the applet‟s executable class file.
CODE is a required attribute that give the name of the file containing your applet‟s
compiled class file which will be run by web browser or appletviewer.
ALT: Alternate Text. The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.
NAME is an optional attribute used to specifies a name for the applet instance.
WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the
applet display area.
VSPACE AND HSPACE attributes are optional, VSPACE specifies the space, in
pixels, about and below the applet. HSPACE VSPACE specifies the space, in
pixels, on each side of the applet
PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with the
get Parameter()method.
Example
import java.awt.*;
import java.applet.*;
JPR-22412 Page 5
Unit-V- Java Applets & Graphics Programming
<HTML>
<Applet code = “hellouser.class” width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM…> tag
JPR-22412 Page 6
Unit-V- Java Applets & Graphics Programming
Program for an applet to accept user name in the form of parameter and print
‘Hello<username>’ [W-15]
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = “hellouser.class” width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
Graphics can be drawn with the help of java. java applets are written to draw
lines, figures of different shapes, images and text in different styles even with the
colours in display.
Every applet has its own area of the screen known as canvas, where it creates the
display in the area specified the size of applet’s space is decided by the attributes of
<APPLET...> tag.
A java applet draws graphical image inside its space using the coordinate system
shown in following fig., which shows java’s coordinate system has the origin (0, 0) in
the upper-left corner, positive x values are to be right, and positive y values are to the
bottom. The values of coordinates x and y are in pixels.
X
(0, 0)
JPR-22412 Page 7
Unit-V- Java Applets & Graphics Programming
1. Write a java applet code and save it with as a class name declared in a program by
extension as a .java.
e.g. from above java code file we can save as a Welcome.java
3. After successfully compiling java file, it will create the .class file, e.g
Welcome.class. then we have to write applet code to add this class into applet.
4. Applet code
<html>
<Applet code= “ Welcome.class” width= 500 height=500>
</applet>
</html>
5. Save this file with Welcome.html in ‘bin’ library folder.
The Graphics class of java includes methods for drawing different types of
shapes, from simple lines to polygons to text in a variety of fonts.
The paint( ) method and a Graphics object is used to display text. To draw
shapes, drawing methods in Graphics class is used which arguments representing end
points, corners, or starting locations of a shape as a values in the applet’s coordinate
system.
Method Description
clearRect( ) Erases a rectangular area of the canvas
copyArea( ) Copies a 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
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled arc
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing color
setFont( ) Seta fonts.
Displaying String:
drawString() method is used to display the string in an applet window
JPR-22412 Page 9
Unit-V- Java Applets & Graphics Programming
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);
5.2.3.1. drawLine( )
The drawLine ( ) method is used to draw line which takes 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.
The syntax is
g.drawLine(x1,y1,x2,y2);
e.g. g.drawLine(20,20,80,80);
Syntax: void drawRect(int top, int left, int width, int height)
This method takes four arguments, the first two represents the x and y co-
ordinates of the top left corner of the rectangle and the remaining two represent the
width and height of rectangle.
Example: g.drawRect(10,10,60,50);
Q. Design an Applet program which displays a rectangle filled with red color
and message as “Hello Third year Students” in blue color. [S-16]
Program-
import java.awt.*;
import java.applet.*;
JPR-22412 Page 10
Unit-V- Java Applets & Graphics Programming
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
Syntax: void drawOval( int top, int left, int width, int height)
Example: g.drawOval(10,10,50,50);
Syntax- void fillOval(int top, int left, int width, int height):
Example g.fillOval(10,10,50,50);
Q. Write a simple applet program which display three concentric circle. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
JPR-22412 Page 11
Unit-V- Java Applets & Graphics Programming
(OR)
HTML Source:
<html> <applet code=”CircleDemo.class” height=300 width=200>
</applet>
</html>
Q. Write a program to design an applet to display three circles filled with three
different colors on screen. [ W-14, W-15 ]
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
Output
JPR-22412 Page 12
Unit-V- Java Applets & Graphics Programming
Example:
g.drawArc(10, 10, 30, 40, 40, 90);
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 x[ ] = {10, 170, 80};
int y[ ] = {20, 40, 140};
int n = 3;
g.drawPolygon(x, y, n);
Q. Write the syntax and example for each of following graphics methods:
1) drawPoly ( ) 2) drawRect ( ) 3) drawOval ( ) 4) fillOval ( )
JPR-22412 Page 13
Unit-V- Java Applets & Graphics Programming
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400>
</applet>*/
5.2.7. Setting color of an Applet
void setBackground(Color.newColor)
where newColor specifies the new color. The class color defines the constant
for specific color listed below.
Example
setBackground(Color.red);
setForeground (Color.yellow);
The following methods are used to retrieve the current background and foreground
color.
Color getBackground( )
JPR-22412 Page 14
Unit-V- Java Applets & Graphics Programming
Color getForeground( )
A font determines look of the text when it is painted. Font is used while painting text
on a graphics context & is a property of AWT component.
Variable Meaning
String name Name of the font
float pointSize Size of the font in points
int size Size of the font in point
int style Font style
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.
To select a new font, you must first construct a Font object that describes that
font. Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
fontName specifies the name of the desired font. The name can be specified
using either the logical or face name.
All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, Monospaced, and Symbol. Dialog is the
font used by once system‟s dialog boxes.
Dialog is also the default if you don‟t explicitly set a font. You can also use
any other fonts supported by particular environment, but be careful—these other fonts
may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of
these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them
together.
For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which is
defined by Component.
It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
JPR-22412 Page 15
Unit-V- Java Applets & Graphics Programming
Q. Describe any three methods of font class with their syntax and example
of each. [W-14, S-15 ]
Sr.
Methods Description
No
1 static Font decode(String str) Returns a font given its name.
Returns true if the invoking object contains the
boolean equals(Object
2 same font as that specified by FontObj.Otherwise,
FontObj) :
it returns false.
3 String toString( ) Returns the string equivalent of the invoking font.
Returns the name of the font family to which the
4 String getFamily( )
invoking font belongs.
Returns the font associated with the system
static Font getFont(String
5 property specified by property. null is returned if
property)
property does not exist.
Returns the font associated with the System
static Font getFont(String property specified by property.
6
property,Font defaultFont) The font specified by defaultFont is returned if
property does not exist.
7 String getFontName( ) Returns the face name of the invoking font.
8 String getName( ) Returns the logical name of the invoking font.
9 int getSize( ) Returns the size, in points, of the invoking font.
10 int getStyle( ) Returns the style values of the invoking font.
Returns the hash code associated with the
11 int hashCode( )
invoking object.
Returns true if the font includes the BOLD style
12 boolean isBold( )
value. Otherwise, false is returned.
Returns true if the font includes the ITALIC style
13 boolean isItalic( )
value. Otherwise, false is returned.
Returns true if the font includes the PLAIN style
14 boolean isPlain( )
value. Otherwise, false is returned.
Example:-
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
Q. Write method to set font of a text and describe its parameters. [S-16]
The AWT supports multiple type fonts emerged from the domain of traditional
type setting to become an important part of computer-generated documents and
JPR-22412 Page 17
Unit-V- Java Applets & Graphics Programming
Fonts have a family name, a logical font name, and a face name. The family
name is the general name of the font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name specifies a specific font, such
as Courier Italic To select a new font, you must first construct a Font object that
describes that font.
One Font constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
Syntax:
public abstract String[ ] getAvailableFontFamilyNames(Locale 1)
Parameters:
l - a Locale object that represents a particular geographical, political, or
cultural region. Specifying null is equivalent to specifying Locale.getDefault().
JPR-22412 Page 18
Unit-V- Java Applets & Graphics Programming
Or
String[ ] getAvailableFontFamilyNames( )
It will return an array of strings that contains the names of the available font families
Important Questions:-
4 Marks Questions:-
1) Write syntax and example of 1) drawString ( ) 2) drawRect ( ) ; 3) drawOval ( )
4) drawArc ( ).
2) Describe following states of applet life cycle : a) Initialization state. b) Running state.
c) Display state
3) State the use of font class. Describe any three methods of font class with their syntax
and example of each.
4) Differentiate applet and application with any four points.
5) State syntax and explain it with parameters for : i)drawRect ( ) ii) drawOral ( )
6) Design an Applet program which displays a rectangle filled with red color and
message as “Hello Third year Students” in blue color.
7) Describe applet life cycle with suitable diagram.
8) Differentiate between applet and application (any 4 points).
9) Write a program to design an applet to display three circles filled with three different
colors on screen.
10) Explain all attributes available in < applet > tag.
JPR-22412 Page 19