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

Applet-HTML Programming2018

An applet is a Java program that runs in a web browser. It is embedded in an HTML page using <applet> tags. An applet has a lifecycle with four stages: 1. Born - When the applet is first loaded, the init() method is called to initialize variables. 2. Running - When the HTML page is displayed, the start() method is called to start the applet running. The paint() method continuously redraws the applet graphics. 3. Idle - When the user leaves the page, the stop() method is called to pause the applet. 4. Dead - When the browser closes, the destroy() method is called to free

Uploaded by

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

Applet-HTML Programming2018

An applet is a Java program that runs in a web browser. It is embedded in an HTML page using <applet> tags. An applet has a lifecycle with four stages: 1. Born - When the applet is first loaded, the init() method is called to initialize variables. 2. Running - When the HTML page is displayed, the start() method is called to start the applet running. The paint() method continuously redraws the applet graphics. 3. Idle - When the user leaves the page, the stop() method is called to pause the applet. 4. Dead - When the browser closes, the destroy() method is called to free

Uploaded by

pradnya sadigale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Object Oriented Programming Methodology

Using Java

Prof: Pradnya Sadigale


(E&TC Department)
SOET-Lohegaon
•An applet is a small application which capable to running within a
browser. It is an internet based program that has gaphical user
interface (GUI) Written in java language .
•It designed to run inside a web browser or in applet viewer
To facilitate the user to animate the garphics and GUI components
like texr box or radio button

•Applet is a special type of program that is embedded in the (in


HTML using <applet> tag) webpage to generate the dynamic
content. It runs inside the browser and works at client side
It embedded in HTML using <applet> tag to generate the dyanamic
content and works at the client side.
Advantage of Applet

•There are many advantages of applet. They are as follows: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.
•IT Describe what a webpage should look
like
•HTML is written in the from of tags,
enclosed in angle brackets like <html>
•A browser read HTML documents &
displays them on screen
•The browser does not display the HTML
tags but uses the tags to decide how to
display the content of the page
•Applet are program that run over the internet browsers
and hence can be transported over the internet and run
over there .
•Applets are Java programs that are integrated into Web
pages.
•When a Web page containing an applet is displayed by a
Web browser the applet is loaded and executed.
•The applet's output is displayed within a subset of the
browser's display area.
•All applets are subclasses of Applet.
•Thus, all applets must import java.applet.
•Applets must also import java.awt.
•AWT stands for the Abstract Window Toolkit.
•Applets run in a window, it is necessary to include
support for that window. it handled with various
AWT methods, such as drawstring( )
•which outputs a string to a specified X,Y Location.
•Once an applet has been compiled, it is included in
an HTML file using the APPLET tag. The applet will
be executed by a Java-enabled web browser when it
encounters the APPLET tag within the HTML file.
APPLET tag :-
Here is an example of such a comment:-
/*<applet code="MyApplet.class" width=200
height=60>
</applet>
*/
Packages in Applet
• java.applet: - applets are programs which come
from a server into a client and get executed on
the client machine. An applet is a program that
comes to the internet server.
• java.awt : - abstract window tool kit.This package
helps to develop GUI.
- The models for event handling techniques
different tools for graphics and images and the
LayoutManger also it facilities the mechanism for
data transfer by cut and paste process through
clipboard .
Java.applet package
•It consists of a single class, the Applet class
& 3 interfaces:-
AppletContext,
Applet Stub, &
Audio Clip.
Creating Applets
public class Class_NAME extends Applet
{
........
}
//MYCLASS : class name
//APPLET :applet class
•Difference between java application and java applet?
With example.
What Makes a Java Applet Different from a Java Application?
Since you now know that applets can use the entire Java API during runtime,
what actually makes an applet an applet? The most important differences
between the two include:
•Unlike traditional Java applications, applets do not invoke a main() method.
•Applets are designed to be embedded within an HTML webpage.
•The applet Đode is autoŵatiĐallLJ doǁŶloaded to the user͛s ŵaĐhiŶe ǁheŶ theLJ
view an HTML webpage with an embedded applet.
•A Java Virtual Machine (JVM) is required to view an applet. In some cases, the
JVM is a browser plug-in, but it can also be a separate runtime environment
iŶstalled loĐallLJ oŶ the user͛s Đoŵputer.
•The JVM creates an instance of the applet class and invokes methods defined
ǁithiŶ the applet duriŶg the applet͛s lifetiŵe.
•The security rules for applets are enforced by the web browser and tend to be
much stricter than the security rules that apply to standalone Java applications.
It is often referred to as a sandbox environment. This is done to prevent
ŵaliĐious Đode froŵ edž eĐutiŶg oŶ a user͛s Đoŵputer at ruŶtiŵe.
•If an applet requires a custom class, it can be downloaded in a single Java
Archive (JAR) file. This means the possibilities are endless because you can
create custom classes as your skill level progresses.
Java Application Java applet
1) Java applications are stand- Java applets run inside a Java
alone Java programs that can browser.
be run by using just the Java Applet run in the context of a web
interpreter (outside the browser ,being typically embedded
browser) within an html page
Applications programming does not
require a web browser to run .they can
created like normal programming
language program .
2) Application can run by itself. Applications cannot run by itself
and requires browser software to
run it.
3) The main() method must be The paint()method should be
capable of accepting an array capable of accepting an array of
of string object string objects
Java Application Java applet
4 No control over the There is some control over
) execution of the program the execution of the program
.
5 Example : Example:
) class Hello import java.applet.Applet;
{ import java.awt.*;
// Your program begins with a /*<applet
call to main( ) CODE="helloworld.class"
public static void WIDTH=400 HEIGHT=100>
main(String args[]) </applet>*/
{ Public class helloworld
System.out.println(" Hello extends Applet
World "); {
} Public void paint(Graphics g)
} {
g.drawString(ˈhello
pw oarikalrd!ˉ,10,10);
ak G
Applet Life Cycle
APPLET LIFE CYCLE
Steps -Applet Life cycle
1.Born or initialization state
2.Running state
3.Idle state
4.Dead or destroyed state
1.Born state
•Applet eŶters the ͚ďorŶ͛ state ǁheŶ it is first loaded this is
achieved by calling the init() method of applet class
1.create objects needed by the applet .
2.set up initial values
3.load image or fonts
4.setup colors
Applet enter into this state only once in its life cycle
because init( ) method is called only once in the beginning.
The init( ) method is the first method to
Syntax :
be called. This is where you should
public void init() initialize variables. This method is called
{ only once during the run time of your
……. applet.
}
2.Running state
Start( ) method:
•The start( ) method is called after init( ).
• It is also called to restart an applet after it has been stopped.
•Hence if the web page left for some time and we go back to that
web page which has an applet ,then the start() method of the applet
is called again.
whereas init( ) is called once—the first time an applet is
loaded—start; Ϳis Đalled eaĐh tiŵe aŶ applet͛s HTML document
is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( )
Paint() method:
The paint( ) method has one parameter of type Graphics.
This parameter will contain the graphics context, which
describes the graphics environment in which the applet is
running.
3.Idle state
Stop() method:
When the page containing the applet is closed or the browser goes
to another page then the stop() method is called . It just stops the
thread running the applet .the applet can be started by the usage of
start() method after stopping it .

4.Destroyed state :
The destroy( )method:
needs to be removed completely from memory. This occurs
automatically by invoking destroy() method when we quit the
browser. An applet gets destroyed only once its life cycle
•The stop( ) method is always called before destroy( ).
Note :
• init(): Initialization occurs when applet is first loaded. Tasks
performed here are creating objects setting initial state, loading
images, fonts etc. and setting parameters.

• start(): Starting occurs after initialization and after stop occurs. Tasks
include starting threads, sending messages to helper objects, or to
tell the applet to start running.

• paint(): This method is to display things how they are to be drawn on


screen whether in the form of text, graphics or background. Redisplay
occurs many times within the life of an applet.

• stop(): Stopping occurs when one leaves a page that contains a


running applet. Threads normally continue running but can be
manually stopped.

• destroy(): Called if current browser session is being terminated.


Frees all resources used by the applet.
APPLET LIFE CYCLE Example:
• The following source code for the
͞SiŵpleLife͟ applet. The siŵpleLife applet
display a descriptive string whenever it
encounters a major milestone in a life ,such
as when the user first visits the page to
applets on.
//Program to demonstrate life cycle of an public void start()
applet {
import java.applet.Applet; addItem("starting... ");
import java.awt.Graphics; }
/*<applet CODE="SimpleLife.class"
WIDTH=400 HEIGHT=100> </applet> */ public void stop()
{
public class SimpleLife extends Applet
{
addItem("stopping... ");
StringBuffer buffer; }
public void init()
{ public void destroy()
buffer = new StringBuffer();
{
addItem("initializing... "); addItem("preparing for
} unloading...");
}
private void addItem(String newWord) /*
{
System.out.println(newWord); javac
buffer.append(newWord); SimpleLife.java
repaint(); appletviewer
}
SimpleLife.java
public void paint(Graphics g) initializing...
{ starting...
//Draw the current string inside the rectangle.
g.drawString(buffer.toString(), 5, 15); stopping...
} preparing for
} unloading...
*/
Overriding update( )
• In some situations, your applet may need to
override another method defined by The AWT,
called update( ).

CALLING REPAINT() METHOD


• Whenever your applet needs to update the information
displayed in its window, it simply calls repaint().
• The repaint( ) method is defined by the AWT.
• It causes the AWT run-time system to execute a call to your
applet’s update( ) method

void repaint(int left, int top, int width, int height)


Applet viewer
• Applet viewer is a command line program to run Java applets.
• It is included in the SDK.
• It helps you to test an applet before you run it in a browser.

• The applet's code gets transferred to the system and then


the Java Virtual Machine (JVM) of the browser executes that
code and displays the output..
• running the applet, the browser should be Java enabled. To
create an applet, we need to define a class that inherits the
Applet.
Method 1)To execute an applet in web browser
ϭͿWrite a applet to displaLJ͞All the Best͟ usiŶg aŶ HTML file.
//save as Luck.java Save Luck.html (same folder)
import java.awt.*;
<html>
import java.applet.*; <body>
public class Luck extends Applet <applet
{ code="Luck.class"width=200
height=150>
public void paint(Graphics g)
</applet>
{ </body>
g.drawString("All the best", 10,10); </html>
}
}
/* C:\>a110>javac Luck.java
C:\>a110>Luck.html
Method 2)To execute an applet in Applet Viewer.
ϭͿWrite aŶ applet to displaLJ͞All the Best͟ usiŶg aŶ HTML file. Use
Applet Viewer to see the output instead of browser.
//save as Luck.java
Save Luck.html (same folder)
import java.awt.*;
import java.applet.*; <html>
<body>
public class Luck extends Applet <applet
{ code="Luck.class"width=200
public void paint(Graphics g) height=150>
{ </applet>
</body>
g.drawString("All the best", 10,10);
</html>
}}
/* C:\>a110>javac Luck.java
C:\>a110>appletviewer Luck.html */
Method 2)To execute an applet in Applet Viewer.
ϭͿWrite aŶ applet to displaLJ͞All the Best͟ usiŶg aŶ HTML file. Use
Applet Viewer to see the output instead of browser.
//save as Luck.java
Save Luck.html (same folder)
import java.awt.*;
import java.applet.*; <html>
lic class Luck extends Applet <body>
pub
<applet
{ code="Luck.class"width=2 00
public void paint(Graphics g) height=150>
{ </applet>
awString("All the best", 10,10); </body>
g.dr
</html>
}}
/* C:\>a110>javac Luck.java
C:\>a110>appletviewer Luck.html */
3)To execute an applet in Applet Viewer without any HTML
File
ϭͿWrite a applet to displaLJ͞All the Best͟ ǁithout usiŶg aŶ HTML file.
import java.awt.*;
import java.applet.*;
/*<applet code="Luck.class"width=200 height=150>
</applet> */
public class Luck extends Applet
{
public void paint(Graphics g)
{
g.drawString("All the best", 10,10);
}}
/*C:\>a110>javac Luck.java
C:\>a110>appletviewer Luck */
Create aŶ applet ǁhiĐh displaLJ͞All The Best͟.
import java.applet.Applet;
import java.awt.*;
/*<applet CODE="helloworld.class" WIDTH=400 HEIGHT=100>
</applet>*/
public class helloworld extends Applet
{
Public void paint (Graphics g)
{
g.draǁStriŶg;͞All The Best͟,ϮϬ,ϮϬͿ;
}}
Applet Method

• Working with Graphics


• Working with Colors
• Working with Fonts
• Using Buttons
• Menu Bars and Menus
• Image Fundamentals: Creating,
Loading,and Displaying
Working with Graphics

• The AWT supports a rich assortment of graphics


methods.
• All graphics are drawn relative to a window. This can
be the main window of an applet, a child window of
an applet, or a stand-alone application window.
• The origin of each window is at the top-left corner
and is 0,0. Coordinates are specified in pixels.
• All output to a window takes place through a graphics
context. A graphics context is encapsulated by the
Graphics class and is obtained in two ways
• It is passed to an applet when one of its
various methods, such as paint( ) or update( )
is called.
• It is returned by the getGraphics( ) method of
Component.
several of the drawing methods.
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
startX,startY and
ends at endX,endY.
The following applet draws several lines:
// Draw lines
import java.awt.*;
import java.applet.*;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
}
}
• Drawing Rectangles
• void drawRect(int top, int left, int width, int height)
• void fillRect(int top, int left, int width, int height)
• void drawRoundRect(int top, int left, int width, int
height,int xDiam, int yDiam)
• void fillRoundRect(int top, int left, int width, int
height,int xDiam, int yDiam)
• void drawRoundRect(int top, int left, int width, int
height,int xDiam, int yDiam)
• A rounded rectangle has rounded corners. The upper-
left corner of the rectangle is at top,left. The
dimensions of the rectangle are specified by width and
height.
• The diameter of the rounding arc along the X axis is
specified by xDiam. The diameter of the rounding arc
along the Y axis is specified by yDiam.
Drawing Ellipses and Circles
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)

The ellipse is drawn within a bounding rectangle whose


upper-left corner is specified by top,left and whose width
and height are specified by width and height.
To draw a circle, specify a square as the boundin
rectangle. The following program draws several ellipses:
Draw Ellipses
import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet {
public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown
here:

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
corner 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 sweepAngle.
• Angles are specified in degrees.
• Zero degrees is oŶ the horizoŶtal, at the three o͛ĐloĐk
position.
• The arc is drawn counterclockwise if sweepAngle is
positive, and clockwise if sweepAngle is negative.
• Therefore, to draǁ aŶ arĐ froŵ tǁ elǀe o͛ĐloĐk to sidž
o͛ĐloĐk, the start aŶgle ǁ ould ďe 9Ϭ aŶd the sǁ eep
angle 180.
import java.awt.*;
import java.applet.*;
/* <applet code="Arcs" width=300 height=200>
</applet> */
public class Arcs extends Applet {
public void paint(Graphics g) {
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);
}
}
Drawing Polygons
It is possible to draw arbitrarily shaped figures using
drawPolygon( ) and fillPolygon( ),
shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)

The polygon’s endpoints are speĐified ďy the Đoordinate


pairs contained within the x and y arrays. The number of
points defined by x and y is specified by numPoints. There
Are alternative forms of these methods in which the
polygon is specified by a Polygon object.
import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet> */
public class HourGlass extends Applet {
public void paint(Graphics g) {
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Working with Colors
The most commonly used forms are shown here:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, green,
and blue. These values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red.
The second color constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23,
green in bits 8 to 15, and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
The final constructor, Color(float, float, float), takes three float values (between 0.0
and 1.0) that specify the relative mix of red, green, and blue.
Once you have created a color, you can use it to set the foreground and/or
background color by using the setForeground( ) and setBackground( ) methods
You can also select it as the current drawing color.
Color Methods :The Color class defines several methods that help manipulate
colors. They are examined here. Using Hue, Saturation, and Brightness The hue-
saturation- brightness (HSB) color model is an alternative to red-green-blue (RGB)
for specifying particular colors. Figuratively, hue is a wheel of color. The hue is
specified with a number between 0.0 and 1.0 (the colors are approximately:
red, orange, yellow, green, blue, indigo, and violet). Saturation is another scale
ranging from 0.0 to 1.0, representing light pastels to intense hues. Brightness
values also range from 0.0 to 1.0, where 1 is bright white and 0 is black. Color
supplies two methods that let you convert between RGB and HSB. They are
shown here:
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[ ] RGBtoHSB(int red, int green, int blue, float values[ ])
HSBtoRGB( ) returns a packed RGB value compatible with the
Color(int) constructor.
RGBtoHSB( ) returns a float array of HSB values corresponding to RGB
integers. If values is not null, then this array is given the HSB values and returned.
Otherwise, a new array is created and the HSB values are returned in it. In either
case, the array contains the hue at index 0, saturation at index 1, and brightness at index 2.
getRed( ), getGreen( ), getBlue( )
You can obtain the red, green, and blue components of a color
independently using
getRed( ), getGreen( ), and getBlue( ), shown here:
int getRed( )
int getGreen( )
int getBlue( )
Each of these methods returns the RGB color component found in
the invoking Color object in the lower 8 bits of an integer.
getRGB( )
To obtain a packed, RGB representation of a color, use getRGB( ),
shown here:
int getRGB( )
The return value is organized as described earlier
Working with Fonts
• The AWT supports multiple type fonts. Fonts have
emerged from the domain of traditional typesetting to
become an important part of computer-generated
documents and displays. The AWT provides flexibility
by abstracting font-manipulation operations and
allowing for dynamic selection of fonts.
• Beginning with Java 2, 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 Mono
spaced. The face name specifies a specific font, such as
Courier Italic. Fonts are encapsulated by the Font class.
Several of the methods defined by Font are listed in
Table .The Font class dePrfoif.n
Dee sk Gtahikaer se variables
epa
Working with Graphics
• We generally use web browsers to run applets. Its not always
mandatory to open a Web browser for running an applet. There is
another way as well. The other way to run an applet is through Java
applet viewer. This is a tool that acts as a test bed for Java applets.
The working of Applet viewer is a bit different from a Web browser,
though they are logically same. The Applet viewer runs on the HTML
documentation, and uses embedded applet tags. The difference in
using the applet viewer and the web browser to run the applet is
that the applet viewer only deals with the applet code not the HTML
cod i.e. it doesn't display HTML code. So we should test our program
in applet viewer and web browser to confirm its working.
• The applet viewer command connects to the documents or
resources designated by urls. It displays each applet referenced by
the documents in its own window.
• The syntax for the applet viewer is:
Drawing Ellipses and Circles
• To draw an ellipse, use drawOval( ). To fill an ellipse,
use fillOval( ). These methods are shown here:

• void drawOval(int top, int left, int width, int height)

• void fillOval(int top, int left, int width, int height)

• The ellipse is drawn within a bounding rectangle


whose upper-left corner is specified
• by top,left and whose width and height are specified
by width and height.
• To draw a circle, specify a square as the bounding
rectangle.
• Where the URL specifies the location of the applet
program and the Options argument specifies how to
run the Java applet. We can use only one option -
debug that starts the applet viewer in the Java
debugger. Using this option we can debug an applet.
• The following program shows how to build an applet
and the HTML file for it. Firstly create a class. Then
start the applet using init method. After that enter a
string as str = "This is my first
applet". Use paintmethod to give the dimensions of
the applet. Beneath that is the HTML file which shows
how to give the body for applet.

You might also like