0% found this document useful (0 votes)
45 views

Chapter 5

Uploaded by

R Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Chapter 5

Uploaded by

R Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit- V:- Java Applets & Graphics

Programming
• Introduction to applets :
• Applet Basics-
• Applet is a special type of program that is embedded in the webpage to
generate the dynamic content.
• It runs inside the browser and works at client side.
• applets are small java programs that are primarily used in internet
computing
• 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
• Every applet is implemented by creating sub class of Applet class
• Advantage of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.
• Drawback of Applet
• Plugin is required at client browser to execute applet.
Differentiate between applet and application

Applet Application

Applet does not use main() method for initiating Application use main() method for initiating
execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in local Application can read from or write to files in local
computer computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local computer. Application can run any program from local
computer
Applet are restricted from using libraries from other Application are not restricted from using
language such as C or C++ libraries from other language
Chain of classes inherited by applet class in java

Java.lang.Object

Java.awt.Component

Java.awt.Container

Java.awt.Panel

Java.applet.Applet
Applet Life Cycle/ Applet Skeleton
• The applet life cycle can be defined as the process of how the object is created,
started, stopped, and destroyed during the entire execution of its application.
• It basically has five core methods namely init(), start(), stop(), paint() and
destroy().

a) Born or initialization state :


• Applet enters the initialization state when it is first loaded.
• The init() method is the first method to run that initializes the applet.
• At this stage the following can be done:
 Create objects needed by the applet
 Set up initial values
 Load images or fonts
 Set up colors
 Initialization happens only once in the life time of an applet.
public void init() {
b) Running state:
• Applet enters the running state when the system calls the start()
method of Applet class.
• The start() method contains the actual code of the applet and starts
the applet.
• 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.
public void start()
{
//implementation
}
c) Idle or stopped state:
• An applet becomes idle when it is stopped from running.
• Stopping occurs automatically when the user leaves the page
containing the currently running applet.
• The stop() method stops the execution of the applet.
• The stop () method is invoked whenever the applet is stopped,
minimized, or moving from one tab to another in the browser.
• stop() method may be overridden to terminate the thread used to run
the applet.
public void stop()
{
//implementation
}
d) Dead state:
• An applet is dead when it is removed from memory.
• This occurs automatically by invoking the destroy method when we
quit the browser.
• The destroy() method destroys the applet after its work is done.
• Destroying stage occurs only once in the lifetime of an applet.
• destroy() method may be overridden to clean up resources like
threads.
• We cannot start the applet once it is destroyed.
public void destroy()
{
//implementation
}
e) Display state:
• Applet is in the display state when it has to perform some output operations on
the screen.
• This happens after the applet enters the running state.
• paint() method is called for this.
• The paint() method belongs to the Graphics class in Java.
• It is used to draw shapes like circle, square, trapezium, etc., in the applet.
• It is executed after the start() method and when the browser or applet windows
are resized.
• Sequence of method execution when an applet is executed:
• init()
• start()
• paint()
• Sequence of method execution when an applet is executed:
• stop()
Applet Tag & Attributes
• APPLET Tag:
• The APPLET tag is used to start an applet from both an HTML document and from an applet
viewer.
• The syntax for the standard APPLET tag:
<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>]
...
• 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.
• ALIGN is an optional attribute that specifies the alignment of the applet. The
possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE, and ABSBOTTOM.
• 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.
Explain <PARAM> tag of applet with suitable example
• To pass parameters to an applet <PARAM… > tag is used.
• Each <PARAM…> tag has a name attribute and a value attribute.
• Inside the applet code, the applet can refer to that parameter by name to find its
value.
• The syntax of <PARAM…> tag is as follows
<PARAM NAME = name1 VALUE = value1>
• To set up and handle parameters, two things must be done.
1. Include appropriate <PARAM..> tags in the HTML document.
2. Provide code in the applet to parse these parameters.
• Parameters are passed on an applet when it is loaded.
• Generally init() method in the applet is used to get hold of the parameters defined
in the <PARAM…> tag.
• The getParameter() method, which takes one string argument representing the
name of the parameter and returns a string containing the value of that
• Example
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); } }
<HTML>
<Applet code = “hellouser.class” width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
Graphics Programming

• 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.,
• Write a simple applet which display message ‘Welcome to Java’.
import java. applet.*;
import java.awt.*;
public class Welcome extends Applet
{
public void paint( Graphics g)
{
g.drawString(“Welcome to java”,25,50);
}
}
/*<applet code= WelcomeJava width= 300 height=300>
</applet>*/
Step to run an Applet

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
2. Compile the java file in command prompt jdk as shown below
C:\java\jdk1.7.0\bin> javac 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.
6. Now write the following steps in command prompt jdk.
C:\java\jdk1.7.0\bin> appletviewer Welcome.java
C:\java\jdk1.7.0\bin> appletviewer Welcome.html
(Shows output in applet viewer)
OR
C:\java\jdk1.7.0\bin> Welcome.html
(Shows output in internet browser)
Graphics Class
• 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( ) Sets fonts.
drawString( )
• Displaying String:
• 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);
 Lines and Rectangle:
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);

• drawRect( )
• The drawRect() method display an outlined rectangle
• 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);
• Circle and Ellipse
• drawOval( ) :
• 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);
• fillOval ( ) :
• Draws an oval within a bounding rectangle whose upper left corner is
specified by top, left. Width and height of the oval are specified by width
and height.
• Syntax- void fillOval(int top, int left, int width, int height);
• Example g.fillOval(10,10,50,50);

• Drawing Arcs :
• 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);
• Drawing polygons :
• 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);
• Drawing polygons
• drawPolygon( ) :
• drawPolygon() method is used to draw arbitrarily shaped figures.
• Syntax- void drawPolygon(int[ ] xPoints, int[ ] yPoints, 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 x[ ] = {10, 170, 80};
int y[ ] = {20, 40, 140};
int n = 3;

g.drawPolygon(x, y, n);
Setting color of an Applet
• Background and foreground color of an applet can be set by using followings methods
void setBackground(Color.newColor)
void setForeground (Color.newColor)
• where newColor specifies the new color.
• The class color defines the constant for specific color listed below.
• Color.black Color.white Color.pink Color.yellow
• Color.lightGray Color.gray Color.darkGray Color.red
• Color.green Color.magenda Color.orange Color.cyan
• Example
setBackground(Color.red);
setForeground (Color.yellow);

• The following methods are used to retrieve the current background and foreground color.
Color getBackground( )
Color getForeground( )
Font class
• 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.
• The Font class defines these variables:
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
Use of 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.
• Syntax to create an object of Font class.
• 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
Methods of font class

Methods Description
static Font decode(String str) Returns a font given its name.

boolean equals(Object FontObj) : Returns true if the invoking object contains the same font as that
specified by FontObj.Otherwise, it returns false.
String toString( ) Returns the string equivalent of the invoking font.
String getFamily( ) Returns the name of the font family to which the invoking font
belongs.
static Font getFont(String property) Returns the font associated with the system
property specified by property. null is returned if property does not
exist.
static Font getFont(String Returns the font associated with the System property specified by
property,Font defaultFont) property. The font specified by defaultFont 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.

You might also like