0% found this document useful (0 votes)
93 views31 pages

Applet Execution Without Main Method

Uploaded by

R Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Topics covered

  • Applet Development,
  • Applet Tag,
  • Applet Drawing Techniques,
  • Applet Parameter Handling,
  • Applet Interaction,
  • Drawing Polygons,
  • Applet Performance,
  • Applet Deployment,
  • Drawing Ovals,
  • Applet Methods Overview
0% found this document useful (0 votes)
93 views31 pages

Applet Execution Without Main Method

Uploaded by

R Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Topics covered

  • Applet Development,
  • Applet Tag,
  • Applet Drawing Techniques,
  • Applet Parameter Handling,
  • Applet Interaction,
  • Drawing Polygons,
  • Applet Performance,
  • Applet Deployment,
  • Drawing Ovals,
  • Applet Methods Overview

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

[Link]

[Link]

[Link]

[Link]

[Link]
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 [Link].*;
import [Link].*;
public class hellouser extends Applet {
String str;
public void init() {
str = getParameter("username");
str = "Hello "+ str; }
public void paint(Graphics g) {
[Link](str,10,100); } }
<HTML>
<Applet code = “[Link]” 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 [Link].*;
public class Welcome extends Applet
{
public void paint( Graphics g)
{
[Link](“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 [Link]
2. Compile the java file in command prompt jdk as shown below
C:\java\jdk1.7.0\bin> javac [Link]
3. After successfully compiling java file, it will create the .class file, e.g
[Link]. then we have to write applet code to add this class into
applet.
4. Applet code
<html>
<Applet code= “ [Link]” width= 500 height=500>
</applet> </html>
5. Save this file with [Link] in ‘bin’ library folder.
6. Now write the following steps in command prompt jdk.
C:\java\jdk1.7.0\bin> appletviewer [Link]
C:\java\jdk1.7.0\bin> appletviewer [Link]
(Shows output in applet viewer)
OR
C:\java\jdk1.7.0\bin> [Link]
(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:
[Link](“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
[Link](x1,y1,x2,y2);
• e.g. [Link](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: [Link](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: [Link](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 [Link](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: [Link](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:
• [Link](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;

[Link](x, y, n);
Setting color of an Applet
• Background and foreground color of an applet can be set by using followings methods
void setBackground([Link])
void setForeground ([Link])
• where newColor specifies the new color.
• The class color defines the constant for specific color listed below.
• [Link] [Link] [Link] [Link]
• [Link] [Link] [Link] [Link]
• [Link] [Link] [Link] [Link]
• Example
setBackground([Link]);
setForeground ([Link]);

• 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:
• [Link], [Link], and [Link]. To combine styles, OR them together.
• For example,
• [Link] | [Link] 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 [Link], 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.

Common questions

Powered by AI

The <APPLET> tag is used to embed an applet in an HTML document, initiating its execution in a web browser or applet viewer. Key attributes of the <APPLET> tag include CODEBASE for specifying the base URL of applet code, CODE for the applet's compiled class file, and WIDTH and HEIGHT for the applet's display area size. Optional attributes like NAME specify the applet instance, ALIGN controls its alignment, and VSPACE and HSPACE determine spacing around the applet. Moreover, the <PARAM> tags within the <APPLET> tag define applet-specific parameters .

The paint() method can be utilized by applets to enhance user experience by rendering dynamic graphics and animations. This method uses the Graphics class to draw shapes, such as rectangles and ovals, display text, and manage colors. By overriding paint(), developers can create visually appealing interfaces with custom designs, such as drawing interactive charts or rendering animations. The coordinate-based graphics system allows precise control over the placement and design, enabling developers to leverage visual elements like colors and text styles through methods like setColor() and setFont().

The Font class in Java applets customizes text appearance by specifying the font's name, style, and size. A font is created via the Font constructor and applied using the setFont() method. Styles can include Font.PLAIN, Font.BOLD, and Font.ITALIC, and different styles may be combined for varied text effects. However, the availability of specific fonts can be a limitation as not all environments support every font. Basic fonts like Dialog, Serif, and Monospaced are universally supported, but relying on others can cause compatibility issues if they aren't available in the user's environment .

Applets differ from standalone Java applications primarily in execution context and security restrictions. Applets are embedded within HTML pages and run inside a browser with no need for a main() method; they are executed starting with the init() method. They have restricted permissions, such as not being able to read from or write to the local file system, run on the local machine, or communicate with other servers for security reasons. In contrast, standalone applications run independently, can access local resources, and use a main() method to start execution .

The destroy() method is responsible for cleaning up resources used by an applet. This method is invoked when the applet is being permanently removed from memory, enabling the applet to perform tasks such as releasing resources or threads. However, once the destroy() method is called, the applet cannot be restarted—it must be completely reloaded to run again. Additionally, destroy() is called only once in the applet's lifecycle, making it essential to efficiently manage resource cleanup within this method .

The core methods in the applet lifecycle are init(), start(), stop(), paint(), and destroy(). The init() method is used to initialize an applet, and it's called once when the applet is first loaded. The start() method is called to begin the applet's execution--it can be invoked multiple times as the applet is restarted. The paint() method, responsible for rendering, is called after the applet starts and whenever the applet needs to redraw its output. The stop() method is invoked when the applet stops running, such as when the user leaves the page. Finally, the destroy() method is called once to cleanup before the applet is unloaded from memory .

Parameters allow external data to be passed into applets, enhancing their functionality by allowing dynamic content. They are defined using the <PARAM> tag in the HTML code, with a NAME and VALUE attribute. Inside the applet, parameters are accessed using the getParameter() method, which takes the parameter's name and returns its value as a string. This mechanism allows the applet to retrieve customized data such as a username to display personalized messages .

The primary benefit of applets is that they enable dynamic content on websites, operating client-side with minimal server load, thus reducing response time. They offer browser compatibility across multiple platforms, enhancing accessibility. However, their drawbacks include requiring plugins for execution, which can deter users; applets also have rigorous security restrictions, limiting access to client-side resources. Furthermore, the need for Java plugins presents compatibility challenges as modern browsers phase out support for applets, making them less viable compared to newer web technologies .

The init() method plays a crucial role in setting up an applet by performing initial configurations necessary for its operation. When an applet is loaded, init() runs first, allowing the applet to create objects it needs, set initial values, load images or fonts, and establish color schemes. This initialization occurs only once, which makes it critical to prepare the applet for execution, ensuring all necessary resources are in place before any user interaction or further execution logic begins .

An applet can manage multiple displays by dynamically adjusting content in response to user interactions or events. By leveraging the repaint() method, which calls paint() again, applets can update their display on-the-fly to reflect changes such as user inputs or live data. Developers can override event-handling methods to respond to user actions, and use logic within the paint() method to render different content conditions, such as switching views or displaying new information. Techniques like double buffering can optimize the display update process to minimize flicker and improve user experience .

You might also like