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

Java Applet

Uploaded by

Yash Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Applet

Uploaded by

Yash Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-60
Topic: Chapter-10 Applet

 Applets are small programs that are primarily used in Internet computing.
They can be transported over the Internet from one computer to another and
run using the AppletViewer or any Web browser that supports Java.

 An applet, like any application program, can do many things for us. It can
perform arithmetic operations, display graphics, play sounds, accept user
input, create animation etc.

Applet Basics:
Before Java, you used HTML to describe the layout of a web page. The basic idea
of how to use applets in a web page is simple, the HTML page must tell the
browser which applets to load and then where to put each applet on the web
page. As you might expect, the tag needed to use an applet must tell the browser
the following.
 From where to get the class files.
 How the applet sits on the web page. (size, location etc)
The browser then retrieves the class files from the Net ( or from the directory on
the user’s machine) and automatically runs the applet, using its Java Virtual
Machine.

Difference between Applet and Application:


Although both the applets and applications are Java programs, there are
significant differences between them.
 Applets do not use the main( ) method for initiating the execution of the code.
Applets, when loaded, automatically call certain methods of Applet class to
start and execute the applet code.
 Unlike stand alone applications, applets cannot be run independently. They
are run from inside a Web page using a special features known as HTML tag.
 Applets cannot read from or write to the files in the local computer.
 Applets cannot communicate with other servers on the network.
 Applets cannot run any program from the local computer.

1 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

All these restrictions and limitations are placed in the interest of security of
systems. These restrictions ensure that an applet cannot do any damage to the
local system.

Writing a First Applet:


Following are the steps involved in developing and testing an applet
 Building an applet code. ( . java file)
 Creating an executable applet (.class file)
 Designing a Web page using HTML tags.
 Preparing the <APPLET> tag.
 Creating HTML file which uses the APPLET tag.
 Testing the applet code by using the appletviewer or Browser.

Applet Inheritance Hierarchy :

Object

Component

Container

Window Panel

`
Frame Applet

2 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following is the program to create “Hello World” applet.


import java.awt.Graphics;
import java.applet.Applet;

public class HelloWorldApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString(“Hello World”,50,25);
}
}

As above mentioned, an applet is a Java class that runs in the web browser or
appletviewer.
Running the Applet:
To execute the applet, you need to carry out two steps.
 Compile your source files into class files.
 And then type Appletviewer <AppletCode.java> on command prompt and hit
enter key to start applet.

Designing a WEB page:


 Recall that Java applets are programs that reside on Web page. In order to run
a Java applet, it is first necessary to have a Web page that references that
applet.

 A Web page basically made up of text and HTML tags that can be interpreted
by a Web browser or an applet viewer.

 Web pages are stored using a file extension .html such as MyApplet.html.
Such files are referred as HTML files. HTML files should be stored in the same
directory as the compiled code of the applets.

3 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Applet tag:
The <APPLET> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. So test the above applet program,
we have to write the following
Hello.html file.
<HTML>
<APPLET CODE=”HelloWorldApplet.class” WIDTH=300 HEIGHT=300>
</APPLET>
</HTML>
Before viewing the applet in a browser, it is a good idea to test it in the
appletviewer program that is a part of the Java SDK. To use the applet viewer in
our example, enter
appletviewer Hello.html
at the command line.

 The HelloWorldApplet implements just one method, the paint method. Most
applets need to handle the paint event.
 This event occurs whenever a part of applet’s visible area is uncovered and
needs to be drawn again.
 The paint method is passed a Graphics object which we have chosen to call g.
 The Graphics class is defined in the java.awt.Graphics package which we have
imported.
 Within the paint method we call Graphics class’s drawString( ) method to
draw the string “Hello World” at the coordinate (50,25). That’s 50 pixels across
and twenty five pixels down from the upper left hand corner of the applet.

4 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-61
Topic: Methods of Graphics Class
The Graphics Class:
 Java’s Graphics class includes methods for drawing many different types of
shapes, from simple lines to polygons to text in a variety of fonts.

 To draw a shape on the screen, we may call one of the methods available in
the Graphics class.

 All the drawing methods have arguments representing end points, corners, or
starting locations of a shape as values in the Frame or Applet coordinate
system.

 To draw a shape, we only need to use the appropriate method with the
required arguments. Following is the list of Graphics class methods.

Method Description
clearRect(int x, int y, int width, int height) Clears the specified rectangle by
filling it with the background color
of the current drawing surface.
copyArea(int x,int y,int w, int height, int dx, Copies an area of the component
int dy) by a distance specified by dx and
dy.
drawArc(int x, int y, int width, int height, int Draws the outline of a circular or
startAngle, int arcAngle) elliptical arc covering the
specified rectangle.
drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current
color, between the points (x1, y1)
and (x2, y2) in this graphics
context's coordinate system.
drawOval(int x, int y, int width, int height) Draws the outline of an oval.

1 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

drawPolygon(int[] xPoints, int[] yPoints, int Draws a closed polygon defined


nPoints) by arrays of x and y coordinates.

drawPolyline(int[] xPoints, int[] yPoints, int Draws a sequence of connected


nPoints) lines defined by arrays of x and y
coordinates.
drawRect(int x, int y, int width, int height) Draws the outline of the specified
rectangle.
drawRoundRect(int x, int y, int width, int Draws an outlined round-
height, int arcWidth, int arcHeight) cornered rectangle using this
graphics context's current color.
drawString(String str, int x, int y) Draws the text given by the
specified string, using this
graphics context's current font
and color.
fillOval(int x, int y, int width, int height) Fills an oval bounded by the
specified rectangle with the
current color.
fillRect(int x, int y, int width, int height) Fills the specified rectangle.
fillRoundRect(int x, int y, int width, int Fills the specified rounded corner
height, int arcWidth, int arcHeight) rectangle with the current color.
getColor() Gets this graphics context's
current color.
getFont() Gets the current font.
setColor(Color c) Sets this graphics context's
current color to the specified
color.
setFont(Font font) Sets this graphics context's font to
the specified font.

2 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-62
Topic: Draw a Polygon in Java Applet
 Polygon is a closed figure with finite set of line segments joining one vertex
to the other.

 The polygon comprises of set of (x, y) coordinate pairs where each pair is the
vertex of the polygon.

 The side of the polygon is the line drawn between two successive coordinate
pairs and a line segment is drawn from the first pair to the last pair.

 Graphics class provides drawPolygon() and fillPolygon() methods to draw or


fill polygon.

 Syntax:
drawPolygon(int[] xPoints, int[] yPoints, int numOfPoints);

Following program demonstrate drawPolygon()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET> */

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet{


public void paint(Graphics g){
int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.drawPolygon(x,y,6);
}
}
Output
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

(100,50) (200,50)

1 2

(250,150) 6 3 (250,150)

5 4
(100,250) (200,250)

Following program demonstrate fillPolygon()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET>*/

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet{

public void paint(Graphics g){


int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.fillPolygon(x,y,6);
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output

Following program demonstrate drawPolyline()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET>
*/
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet{

public void paint(Graphics g){


int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.drawPolyline(x,y,6);
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-63
Topic: Color and Font

Color:
We can also change the draw of fill color using setColor() method of Graphics
class.
Syntax:
void setColor (Color clr)
To set color we need to pass object of Color class which is declared in AWT
package. There are two methods to pass this object
(i) By calling color class constructor
Color (int red, int green, int blue)

Red Green Blue


0 0 0 Black
255 0 0 Red
0 255 0 Green
0 0 255 Blue
255 255 0 Yellow
255 0 255 Magenta
0 255 255 Cyan
127 127 127 Gray
255 255 255 White

(ii) By using predefined color objects


Color.BLACK
Color.WHITE
Color.RED
Color.CYAN
Color.GREEN etc.

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Program to demonstrate Color object


/* <applet code="ColorApplet.class" width=700 height=700>
</applet> */
import java.awt.*;
import java.applet.*;
public class ColorApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(new Color(255,0,0));
g.drawString("Color Demonstration", 50,30);
g.drawLine(50,50,300,50);
g.fillRect(50,60,100,100);

g.setColor(Color.YELLOW);
g.fillOval(50,180,100,100);
}
}

Font:

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

We can also change the font of text using setFont() method of Graphics class.
Syntax:
void setFont (Font font)
To set font we need to pass the object of Font class which is declared in AWT
package. The constructor of Font class takes three arguments.
Font(String fontName, int style , int size)

Constants for style parameter


FONT.PLAIN 0
Font.BOLD 1
Font.ITALIC 2
Fotnt.BOLD+Font.ITALIC 3

e.g. First create font object


Then call setFont() method and pass font object to set a font in Graphics.

Font font = new Font(“Arial”,Font.BOLD, 30);


g.setFont(font);

Program to demonstrate Font object


/* <applet code="FontApplet.class" width=700 height=700>
</applet> */

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

public class FontApplet extends Applet


{
public void paint(Graphics g)
{
g.setColor(new Color(255,0,0));

g.setFont(new Font("Arial", Font.PLAIN, 30));


g.drawString("Font Demonstration", 50,50);

g.setFont(new Font("Arial",Font.BOLD,30));

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

g.drawString("Font Demo", 50,100);

g.setFont(new Font("Arial",Font.BOLD+Font.ITALIC,30));
g.drawString("Font Demo", 50,150);
}
}

Methods of Font Class


Sr. No. Return Type Method
1 String getName()
Returns the font name.
2 int getStyle ()
Returns the font style.
3 int getSize()
Returns the font size.
4 boolean isBold ()
Returns true if the font style is bold.
5 boolean isItalic ()
Returns true if the font style is italic.
6 boolean isPlain ()
Returns true if the font style is plain.

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-64
Topic: Applet Life Cycle

Applet lifecycle :
Every java applet inherits a set of default behavior from the applet class. As a
result when can applet is loaded it undergoes a series of changes in its state as
shown in the following figure-

Begin
(Load Applet) init ( )
Born

start ( )

paint ( ) stop ( )

Running Idle

start ( )
destroy ( )

(Exit from browser)


Dead

End

Four method in applet class gives the framework on which we can build any
applet.
(i) init ( ) {initialization state}
This method is used for whatever initialization is needed for your applet. It is
automatically called by the browser when java creates the object for the first
time. The initialization occurs only once in the applet lifecycle.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

(ii) start ( ) {running state}


This method is automatically called after java calls the init ( ) method. It is
also called whenever the user returns to the page, containing the applet after
having gone off two other pages.
(iii) stop ( ) {ideal state}
This method is automatically called when the user moves off from the applet
page to other page.
(iv) destroy ( ) {Dead state}
Java call this method when the browser is closed and it destroy the applet
object from the memory.

Methods of Applet Class


1) void init()
- Called by browser when the applet is loaded.
2) void start()
- Called by browser to inform the applet is running.
3) void stop()
- Called by browser to inform the applet is entered in idle state.
4) void destroy()
- Called by browser to inform the applet object is destroyed from the
memory.
5) String getParameter(String name)
- Returns the value of the named parameter passed from the web page
6) void showStatus(String message)
- Display the specified message in the status bar of the browser.

Skeleton of Applet program :


public class LifeApplet extends Applet
{
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

//override init() method to perform any kind of initialization


public void init(){
}
//override start() method to start any thread activity.
public void start(){
}
//override stop() method to stop thread activity.
public void stop(){
}
//override destroy() method to release resources
public void destroy(){
}
}

Difference between Application and Applet :


Application Applet
1) Applications are stand-alone 1) Applets are small program that are
programs that can be run designed to be included in the webpage
independently without a browser. and they run inside browser or applet
viewer.
2) Java application has full access 2) Applet has no disk access or file
to local file system. system access.
3) It requires a main ( ) method of 3) It does not require main ( ) method for
its execution. its execution.
4) Application can run program 4) Applet cannot run process from the
from the local system. local machine
5) Application program is used to 5) An Applet program is used to perform
perform same task directly for small task in the webpage.
the user.
6) It can access all kind of resources 6) It can access only browser specific
available on the system. services.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-65
Topic: Passing Information to Applet

Applet tag and It’s Attributes:


 The basic form of APPLET tag is
<APPLET CODE=”HelloApplet.class” WIDTH=100 HEIGHT=100>

 As you seen, the CODE attributes gives the name of the class file and must
include the .class extension.

 The WIDTH and HEIGHT attributes size the window that will hold the applet.

 The text between the <APPLET> and </APPLET> tags is displayed only if the
browser cannot show applets.

 These tags are required. If any are missing, the browser cannot load your
applet.

Applet Attributes for Positioning:


 CODE
This attribute gives the name of the applet’s class file. The CODE attribute
specifies only the name of the class that contains the applet class.

 CODEBASE
This optional attribute tells the browser that your class files are found below
the directory indicated in the CODEBASE attribute.

 WIDTH, HEIGHT
These attributes are required and give the width and height of the applet,
measured in pixels.

 ALIGN
This attributes specified the alignment of the applet. Possible values are as follows
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

LEFT – Places the applet at the left margin of the page.


RIGHT – Places the applet at the right margin of the page.
BOTTOM – Places the bottom of the applet at the bottom of the text in the current line.
TOP - Places the top of the applet with the top of the text in the current line.
MIDDLE- Places the middle of the applet with the baseline of the current line.

Passing Information to Applets:


Just as applications can use command line information, applets can use
parameters that are embedded in the HTML file. This is done via the HTML tag
called PARAM along with attributes that you define. For example, suppose you
want to let the web page determine the style of the font to use in your applet.
You could use the following tag.

<APPLET CODE=”FontParaApplet.class” WIDTH=200 HEIGHT=200>


<PARAM NAME=”font” VALUE=”Helvetica” >
</APPLET>

You then pick up the value of the parameter, using the getParameter ( ) method
of the Applet class, as in the following example

public class FontParaApplet extends Applet


{
pubic void init( )
{
String fontName= getParameter(“font”);
....
}
}
Parameters are always returned as Strings. You need to convert the string to a
numeric type if that is what is called for.

Example: Write an applet to accept username in the form of parameter and print
“Hello <username>” in the Applet.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

1) hello.html
<HTML>
<APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>
<param name="username" value="Atul">
</APPLET>
</HTML>

2) MyApplet.java

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

public class MyApplet extends Applet {

public void paint(Graphics g){

Font f = new Font("Times New Roman", Font.ITALIC, 30);


String name = getParameter("username");
g.setFont(f);
g.drawString("Hello "+name,50,30);

}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Obtaining Font List from local system


To list all the fonts available to you in a Java application, use the

String [] fontNames=GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames()

method of the GraphicsEnvironment class, which technically returns an array of


all the font family names it finds on the local system.
Here’s a small but complete sample Java program that prints out all the fonts
(font family names):

import java.awt.*;
public class ListOfFonts
{

public static void main(String[] args)


{
String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();

for ( String fontName : fonts )


{
System.out.println(fontName);
}
}
}

Output:

You might also like