You are on page 1of 55

Java Applets

Introduction to Java Applet Programs


• Applications are stand alone programs
– executed with Java interpreter

• Applet is a small program


– can be placed on a web page
– Used in Internet computing
– will be executed by the web browser
– give web pages “dynamic content”
– Run using appletviewer or Java enabled web browser

2
Java Applets
• Built using one of general definitions of applets
– Applet class
– JApplet class
• Java applets
– Draws graphics in a defined screen area
– Plays sound
– Accept user input
– Create animation
– Enable user interaction with GUI elements
– It is a container which can hold GUI components
– An applet is a subclass of Panel
– There is no main method.
3
Applets
• Applet
– Program that runs in
• appletviewer
• Web browser
– Executes when HTML (Hypertext Markup Language)
document containing applet is opened
• For security reasons, applets run in a sandbox: they
have no access to the client’s file system
• Two types of Applet
1) Local Applet
2)Remote Applet
4
Applets
• Local Applet
– Developed loacally and stored in local system
– Internet Connection is not required
• Remote Applet
– Developed remotely and stored in remote system
connected to the Internet
– Internet Connection is required
– We must know the applets address on the web i.e
URL
The hierarchy of Applet

java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
Applets and Web Pages – HTML
• Embedding Java applets
– Insert applet tags
<APPLET>
</APPLET>
• Call the specific applet by its file name
<APPLET CODE = "Whatever.class"
WIDTH = nnn HEIGHT = mmm>
<\APPLET>
Where nnn and mmm are specific pixel sizes

7
Applet methods
public void init ()
public void start ()
public void stop ()
public void destroy ()
public void paint (Graphics)

Also:
public void repaint()
public void update (Graphics)
public void showStatus(String)
public String getParameter(String)
Life Cycle of Applet
The applet states include:
1. Born or initialization
state
2. Running state
3. Idle or stopped state
4. Dead or Destroy state
public void init ( )
• Applet is in initialization state
• This is the first method to execute
• Executes only once in the applets life cycle
• place to initialize variables
• Load images, fonts or colors
• It is the best place to define the GUI Components
(buttons, text fields, scrollbars, etc.), lay them out,
and add listeners to them
• Almost every applet will have an init( ) method
public void start ( )
• Called after init( )
• Applet is in Running state
• May be called more than once in the applets life
cycle
• Called each time the page is loaded and restarted
• Used mostly in conjunction with stop( )
• start() and stop( ) are used when the Applet is
doing time-consuming calculations that you don’t
want to continue when the page is not in front
public void stop( )
• Called when the browser leaves the page
• Applet is in Idle state
• Called just before destroy( )
• May be called more than once in the applets life
cycle
• When we leave the page containing currently
running applet, stop() method called
automatically.
• Used mostly in conjunction with start()
public void destroy( )
• Called after stop( )
• Applet is in dead or destroy state
• Executes only once in the applets life cycle
• Applet is removed from memory
• Used to explicitly release system resources
(like threads)
• System resources are usually released
automatically
public void paint(Graphics g)
• Applet is in display state
• Called immediately after the applet enters into
running state
• paint() method is inherited from Component class
• Needed if we want to do any drawing or painting
• Displays the result of applet code on the screen
• It requires Graphics object as an argument
• Never call paint(Graphics), call repaint( )
repaint( )

• Call repaint( ) when we have to show


changes made to an applet on the screen
• repaint( ) is a request
• When you call repaint( ), Java schedules a
call to update(Graphics g)
update( )
• When we call repaint( ), Java schedules a
call to update(Graphics g)
• Here's what update does:
public void update(Graphics g)
{
paint(g);
}
Applet vs Application
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 to
files in local computer 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 from Application can run any program
local computer from local computer

Applet are restricted from using Application are not restricted from
libraries from other language such as using libraries from other language
C or C++ .
Applet tag
•The HTML <applet> tag specifies an applet.

•It is used for embedding a Java applet within


an HTML document

•The only mandatory attributes are CODE,


WIDTH, and HEIGHT.
Syntax: Applet tag
<APPLET
CODEBASE = codebaseURL
CODE = appletFile ...or... OBJECT = serializedApplet
ALT = alternateText
NAME = appletInstanceName
WIDTH = pixels
HEIGHT = pixels
ALIGN = alignment
VSPACE = pixels
HSPACE = pixels >
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>
</APPLET>
Applet tag Example
• simple APPLET tag:

<applet code="MyApplet.class" width=100


height=140></applet>

This tells the viewer or browser to load the


applet whose compiled code is in
MyApplet.class and to set the initial size of the
applet to 100 pixels wide and 140 pixels high.
Sample Applet Program

/*<applet code= “WelcomeJava.class” 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);
}
}
Parameter Passing – Applet
• Similar to command line arguments
• Parameters are also passed from HTML files to
Java applets when it is loaded.
– The HTML file passes parameters as String types,
therefore they need to be converted if used as
another type.
– The parameters are initialized in applet tag section
of HTML file and retrieved in init() method of Java
applet. This is done using getParameter() method.
Passing Parameters to Applet

• User defined parameters can be supplied to an


applet using <PARAM…..> tags.
• PARAM tag can be used to specify different
 colors,
 fonts,
 URLs or
 other data to be used by the applet.
To set up and handle parameters, two things
must be done
1. Include appropriate <PARAM...>tags in the HTML document.

The syntax of <PARAM..> tag


<Applet code=”any.class” height=xxx width=xxx>
<PARAM NAME = name1 VALUE = value1>
</Applet>

NAME: attribute name


VALUE: value of attribute named by corresponding PARAM NAME.

2. Provide code in the applet to parse these parameters.

The Applet access their attributes using the getParameter method. The
syntax is :
String getParameter(String name);
import java.awt.*;
import java.applet.*;
/*<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username " VALUE = "VVP" > </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);
}
}
Graphics class
• AWT supports rich set of graphics methods.
• The origin of each window is at the top-left
corner and it is (0,0).
• Co-ordinates are specified in pixels.
• Graphics context is encapsulated by Graphics
class.
• It is passed to an applet when paint() or
update() is called.
Coordinate System
origin of each window
(top-left corner)

(0,0) (width,0)

(0,height) (width, height)


Graphics class methods

1) drawString( )
• To draw string.
• Syntax:
void drawString(String str, int x, int y)
• Example:
g.drawString(“Hello”,50,100);
Graphics class methods

2) drawLine( )
• To draw line
• Syntax:
void drawLine(int startX,int startY,int endX, int endY)
• Example:
g.drawLine(10,10,50,50);
Graphics class methods

3) drawOval( )
• To draw an Ellipses or circles
• To draw Circle, width and height must be same.
• Syntax:
void drawOval(int top, int left, int width, int
height)
• Example:
g.drawOval(10,10,50,50);
Graphics class methods

4) fillOval( )
• To fill an Ellipses or circles
• To fill Circle, width and height must be same.
• Syntax:
void fillOval(int top, int left, int width, int height)
• Example:
g.fillOval(10,10,50,50);
Graphics class methods

5) drawRect( )
• To draw an rectangle or square
• To draw square, width and height must be same.
• Syntax:
void drawRect(int top, int left, int width, int
height)
• Example:
g.drawRect(10,10,50,50);
Graphics class methods

6) fillRect( )
• To fill an rectangle or square
• To fill square, width and height must be same.
• Syntax:
void fillRect(int top, int left, int width, int height)
• Example:
g.fillRect(10,10,50,50);
Graphics class methods

7) drawRoundRect( )
• To draw an rounded rectangle or square
• Syntax:
void drawRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)
• Example:
g.drawRoundRect(10,10,50,50,10,10);
Graphics class methods

8) fillRoundRect( )
• To fill an rounded rectangle or square
• Syntax:
void fillRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)
• Example:
g.fillRoundRect(10,10,50,50,10,10);
Graphics class methods

9) drawPolygon( )
• To draw any arbitrarily shaped figures
• Syntax:
void drawPolygon(int x[],int y[],int numPoints)
• Example:
int x[]={50,100,150};
(100,50)
int y[]={150,50,150};
g.drawPolygon(x,y,3);

(50,150) (150,150)
Graphics class methods

10) fillPolygon( )
• To fill any arbitrarily shaped figures
• Syntax:
void fillPolygon(int x[],int y[],int numPoints)
• Example:
int x[]={50,100,150};
(100,50)
int y[]={150,50,150};
g.fillPolygon(x,y,3);

(50,150) (150,150)
Graphics class methods

11) drawArc( ) and fillArc()


• To draw an arc drawArc() method is used.
• To fill an arc fillArc() method is used.
• Arc is drawn within bounded rectangle.
• Syntax:
void drawArc(int top, int left, int width, int height,
int startAngle,sweepAngle)

void fillArc(int top, int left, int width, int height, int
startAngle,sweepAngle)
drawArc( ) and fillArc()
• start_angle is starting angle of arc
• sweep_angle is degree around the arc
• It is drawn from startAngle through the angular
distance specified by sweepAngle.
• It is drawn anticlockwise if sweepAngle is positive
and clockwise if sweepAngle is negative.
900

1800 1800 00

2700
• Example: g.drawArc(10, 10, 30, 40, 40, 90);

• Example: g.drawArc(10, 10, 30, 40, 270, -135);

900

450

1800 00
-1350

2700
Color class
• Java deals with color through the Color class
defined in java.awt package
• provides methods for setting the current
foreground and background colors
• color model uses 24-bit color
• color is represented as a combination of red,
green, and blue values
• Each component of the color can have a
number between 0 and 255
• For ex: 0,0,0 is black, 255,255,255 is white
Using Color objects
• The Color class defines a set of standard color
objects. Color Name RGB Value
Color.white 255,255,255
Color.black 0,0,0
Color.lightGray 192,192,192
Color.gray 128,128,128
Color.darkGray 64,64,64
Color.red 255,0,0
Color.green 0,255,0
Color.blue 0,0,255
Color.yellow 255,255,0
Color.magenta 255,0,255
Color.cyan 0,255,255
Color.pink 255,175,175
Color.orange 255,200,0
Using Color objects
• We can use any combination of red, green,
and blue values to construct a color object
• Constructor:
Color(int redValue,int greenValue,int blueValue)
• For ex:
– create a new color object:
Color c = new Color(140,140,140);
Setting background and foreground colors
• set the background and foreground colors using the
setBackground() and setForeground() methods.
• Both of these methods are defined in the
java.awt.Component class
1) setBackground()
• The setBackground() method sets the background
color of the applet.
• It takes a single argument, a Color object:
• Syntax: setBackground(Color c)
• For ex:
setBackground(Color.green);
Setting background and foreground colors
2) setForeground()
• The setForeground() method sets the
foreground color of the applet.
• It affects everything that has been drawn on
the applet
• It takes a single argument, a Color object:
• Syntax: setForeground(Color c)
• For ex:
setForeground(Color.red);
Setting current colors
3) setColor()
• to set the current color to be that color object,
Use the setColor() method (a method for
Graphics objects)
• After setting the current color, all drawing
operations will occur in that color.
• It takes a single argument, a Color object:
• Syntax: setColor(Color c)
• For ex: g.setColor(Color.green);
Getting colors
4) getColor() : to retrieve the current graphics
color, use the getColor() method (a method for
Graphics objects)
• Syntax: Color getColor()
• For ex: Color c=g.getColor();
5) getBackground()
• to retrieve the current background color, use
getBackground() method.
• Syntax: Color getBackground()
• For ex: Color c=getBackground();
Getting colors
6) getForeground()
• to retrieve the current foreground color, use
getForeground() method
• Syntax: Color getForeground()
• For ex: Color c=getForeground();
Font class
• Font class defined in java.awt package
• The Font class represents a given font-its name,
style, and point size.
• Fonts class requires foll. 3 things:

– font name: Serif, Sans-serif, Monospaced,


Dialog, DialogInput, TimesRoman ,Helvetica
Courier
– font style: plain, bold, italic
– font size: a positive integer
• Font class provides a method of specifying and using
fonts.
Font class
• Fonts class defines 3 constants:
Font.PLAIN
Font.BOLD
Font.ITALIC
• Styles can be combined: Font.BOLD|Font.ITALIC

• Fonts class defines 3 variables:


1. String name : The name of the font.
2. int style : The style of the font
3. int size: The name of the font.
• Constructor: Font(String name, int style, int size)
• For ex:
Font f = new Font("Times New Roman", Font.ITALIC, 12);
• To set the Font setFont() method defined by Graphics class is used.
g.setFont(f);
Font class Methods
Method Description
Returns the family name of this
String getFamily()
Font.
String getFontName() Returns the font face name of
this Font.
Font getFont(String nm) Returns a Font object from the
system properties list.
int getSize() Returns the point size of this
Font.
int getStyle() Returns the style of this Font
boolean isBold() Indicates whether or not this
Font object's style is BOLD.
boolean isItalic() Indicates whether or not this
Font object's style is ITALIC.
boolean isPlain() Indicates whether or not this
Font object's style is PLAIN
GraphicsEnvironment class
• It specifies the graphics environment
• It is abstract class.
• It consists of a number of GraphicsDevice objects and Font
objects.
• GraphicsDevice objects are typically screens or printers.
• Methods of GraphicsEnvironment
Method Description
Returns an array containing a one-
Font[ ] getAllFonts()
point size instance of all fonts
available in this Environment.
String[ ] getAvailableFontFamilyNames() Returns an array containing the
names of all font families in this
Environment
static GraphicsEnvironment
Returns the local
getLocalGraphicsEnvironment()
GraphicsEnvironment.
Initializing GraphicsEnvironment
• It is abstract class. So it cant be instantiated directly.
• The getLocalGraphicsEnvironment() of the GraphicsEnvironment
class is used.
• For ex:
GraphicsEnvironment ge=
GraphicsEnvironment. getLocalGraphicsEnvironment();
• This class is used to get all available fonts in the system.
Write a program to display all available fonts in the system using getAvailableFontFamilyName().

/*<applet code="GetAvailableFonts" width=200 height=200> </applet> */

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

public class GetAvailableFonts extends Applet


{
public void paint(Graphics g)
{
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();

String fontNames[] = ge.getAvailableFontFamilyNames();


int y = 20;
for(int i=0; i < fontNames.length; i++)
{
g.drawString(fontNames[i], 10, y);
y += 20;
}
}
}
Write a program to display all available fonts in the system using getAllFonts().

/*<applet code=“AllFonts.class" width=200 height=200> </applet> */

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

public class AllFonts extends Applet


{
public void paint(Graphics g)
{
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();

Font fnt[]=ge.getAllFonts();
int y = 20;
for(int i=0; i <fnt.length; i++)
{
g.drawString(fnt[i]+"", 10, y);
y += 20;
}
}
}

You might also like