0% found this document useful (0 votes)
20 views12 pages

Unit4 AppletsinJavapdf 2024 10 01 15 45 57

Applets are small Java programs that run in web browsers, designed to enhance website interactivity. They follow a defined life cycle with methods such as init(), start(), stop(), and destroy(), and utilize the Graphics class for rendering shapes and text. Event handling in applets is managed through interfaces like ActionListener and MouseListener, allowing for user interaction.

Uploaded by

harleensingh985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views12 pages

Unit4 AppletsinJavapdf 2024 10 01 15 45 57

Applets are small Java programs that run in web browsers, designed to enhance website interactivity. They follow a defined life cycle with methods such as init(), start(), stop(), and destroy(), and utilize the Graphics class for rendering shapes and text. Event handling in applets is managed through interfaces like ActionListener and MouseListener, allowing for user interaction.

Uploaded by

harleensingh985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Introduction to Applets

Definition

An applet is a small Java program that can be embedded in a web page and run in the context of
a web browser. Unlike standalone applications, applets are designed to be downloaded from a
server and executed on the client side.

An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.

Applets are used to make the website more dynamic and entertaining.

Characteristics

 Platform Independence: Applets can run on any platform that supports a Java-enabled
browser.
 Security: Applets run in a restricted environment (sandbox) to prevent malicious actions,
such as accessing the local file system.
 User Interface: Applets can create graphical user interfaces using AWT (Abstract
Window Toolkit) or Swing.

Use Cases

 Interactive web applications (e.g., games, simulations).


 Educational tools and demonstrations.

Important points :
1. All applets are sub-classes (either directly or indirectly)
of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a
web browser or an applet viewer. JDK provides a standard applet viewer
tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println().
Rather it is handled with various AWT methods, such as drawString().
2. Applet Class
Overview

The java.applet.Applet class is the base class for creating applets. It provides essential
methods and functionalities for applet development.

Key Methods

 init(): Called when the applet is first loaded; used for initialization.
 start(): Invoked when the applet is started (after initialization); used for starting threads
or animations.
 stop(): Called when the applet is stopped (e.g., when the user navigates away from the
page).
 destroy(): Invoked when the applet is destroyed; used for cleanup operations.

Example:

import java.applet.Applet;

import java.awt.Graphics;

public class MyApplet extends Applet {

public void init() {

// Initialization code

public void start() {

// Code to start the applet

public void stop() {


// Code to stop the applet

public void destroy() {

// Cleanup code

public void paint(Graphics g) {

// Drawing code

g.drawString("Hello, Applet!", 20, 20);

Applet Life Cycle


Stages of Life Cycle

1. Initialization (init): This is where the applet is initialized, and resources are allocated.
This method is called only once in the applet's life. The init( ) method is the first method
to be called. This is where you should initialize variables. This method is called only
once during the run time of your applet.
2. Starting (start): After initialization, the start() method is called, allowing the applet to
execute code such as animations or thread starting. The start( ) method is called after init(
). It is also called to restart an applet after it has been stopped. Note that init( ) is called
once i.e. when the first time an applet is loaded whereas start( ) is called each time an
applet’s HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).
3. The paint( ) method -The paint( ) method is called each time an AWT-based applet’s
output must be redrawn. This situation can occur for several reasons. For example, the
window in which the applet is running may be overwritten by another window and then
uncovered. Or the applet window may be minimized and then restored.

paint( ) is also called when the applet begins execution. Whatever the cause, whenever
the applet must redraw its output, paint( ) is called.

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.

4. Stopping (stop): The stop() method is called when the user leaves the page, allowing
the applet to pause ongoing processes. The stop( ) method is called when a web browser
leaves the HTML document containing the applet—when it goes to another page, for
example. When stop( ) is called, the applet is probably running. You should use stop( ) to
suspend threads that don’t need to run when the applet is not visible. You can restart
them when start( ) is called if the user returns to the page.
5. Destruction (destroy): Finally, when the applet is about to be destroyed, the destroy()
method is called to free resources. The destroy( ) method is called when the environment
determines that your applet needs to be removed completely from memory. At this point,
you should free up any resources the applet may be using. The stop( ) method is always
called before destroy( ).
Graphics in Applets
Drawing in Applets

Graphics in applets are drawn using the Graphics class, which provides methods for rendering
shapes, text, and images.

Common Graphics Methods

 drawString(String str, int x, int y): Draws a string at the specified coordinates.
 drawLine(int x1, int y1, int x2, int y2): Draws a line between two points.
 drawRect(int x, int y, int width, int height): Draws a rectangle.
 fillRect(int x, int y, int width, int height): Fills a rectangle.
 setColor(Color c): Sets the color for subsequent drawing operations.

Example:

public void paint(Graphics g) {

g.setColor(Color.RED);

g.drawString("Drawing in Applet", 20, 20);

g.drawLine(20, 30, 100, 30);

g.fillRect(20, 40, 60, 30);

}
// A Hello World Applet

// Save file as HelloWorld.java

import java.applet.Applet;

import java.awt.Graphics;

// HelloWorld class extends Applet

public class HelloWorld extends Applet

// Overriding paint() method

@Override

public void paint(Graphics g)

g.drawString("Hello World", 20, 20);

Explanation:

The above java program begins with two import statements. The first import
statement imports the Applet class from applet package. Every AWT-
based(Abstract Window Toolkit) applet that you create must be a subclass (either
directly or indirectly) of Applet class. The second statement import the Graphics
class from AWT package.
The next line in the program declares the class HelloWorld. This class must be
declared as public because it will be accessed by code that is outside the program.
Inside HelloWorld, paint( ) is declared. This method is defined by the AWT and
must be overridden by the applet.

Inside paint( ) is a call to drawString( ), which is a member of the Graphics class.


This method outputs a string beginning at the specified X,Y location. It has the
following general form:

void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the
upper-left corner is location 0,0. The call to drawString( ) in the applet causes the
message “Hello World” to be displayed beginning at location 20,20.

Notice that the applet does not have a main( ) method. Unlike Java programs,
applets do not begin execution at main( ). In fact, most applets don’t even have a
main( ) method. Instead, an applet begins execution when the name of its class is
passed to an applet viewer or to a network browser.

Running the HelloWorld Applet :

After you enter the source code for HelloWorld.java, compile in the same way
that you have been compiling java programs(using javac command). However,
running HelloWorld with the java command will generate an error because it is
not an application.

java HelloWorld

Error: Main method not found in class HelloWorld,


please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An
applet viewer executes your applet in a window. This is generally the
fastest and easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser : To execute an applet in a web
browser we have to write a short HTML text file that contains a tag that loads
the applet. We can use APPLET or OBJECT tag for this purpose. Using
APPLET, here is the HTML file that executes HelloWorld :
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area
used by the applet. The APPLET tag contains several other options. After
you create this html file, you can use it to execute the applet.
NOTE : Chrome and Firefox no longer supports NPAPI (technology required
for Java applets). Refer here
2. Using appletviewer : This is the easiest way to run an applet. To execute
HelloWorld with an applet viewer, you may also execute the HTML file
shown earlier. For example, if the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html

3. appletviewer with java source file : If you include a comment at the


head of your Java source code file that contains the APPLET tag then your
code is documented with a prototype of the necessary HTML statements,
and you can run your compiled applet merely by starting the applet viewer
with your Java source code file. If you use this method, the HelloWorld
source file looks like this :
 Java
//code to illustrate paint

//method gets called again

//and again

import java.applet.*;// used

//to access showStatus()

import java.awt.*;//Graphic

//class is available in this package

import java.util.Date;// used

//to access Date object

public class GFG extends Applet

public void paint(Graphics g)

Date dt = new Date();

super.showStatus("Today is" + dt);

//in this line, super keyword is

// avoidable too.

}
Event Handling in Applets
Overview

Event handling in applets is managed through the event model of Java. Applets can respond to
various events such as mouse clicks, key presses, and window events.

Key Interfaces

 ActionListener: Used for handling button clicks and menu selections.


 MouseListener: Handles mouse events (clicks, enters, exits).
 KeyListener: Captures keyboard events.

Implementing Event Handling

To handle events, an applet needs to implement the relevant listener interface and override its
methods.

Example:

import java.applet.Applet;

import java.awt.Button;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MyApplet extends Applet implements ActionListener {

Button button;

public void init() {

button = new Button("Click Me");

button.addActionListener(this);
add(button);

public void actionPerformed(ActionEvent e) {

// Code to execute when the button is clicked

System.out.println("Button was clicked!");

Summary

 Applets are small Java applications designed to run in web browsers.


 They have a defined life cycle with four primary methods: init(), start(), stop(),
and destroy().
 Graphics are rendered using the Graphics class, allowing various shapes and text to be
drawn.
 Event handling is achieved through interfaces like ActionListener and MouseListener,
enabling interactivity.

You might also like