[go: up one dir, main page]

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

Chapter 2

The document discusses Java applets, including their overview, history, types, key features, life cycle, execution environments, and the applet tag. Java applets are small Java programs that run within web browsers to provide interactive content on web pages.
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 views14 pages

Chapter 2

The document discusses Java applets, including their overview, history, types, key features, life cycle, execution environments, and the applet tag. Java applets are small Java programs that run within web browsers to provide interactive content on web pages.
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/ 14

CHAPTER TWO

JAVA APPLET

1.1. Overview of Java Applets:

Java Applets are small Java programs that run within a web browser, typically enhancing web
pages with interactive content. They provide a way to create dynamic and engaging user
interfaces directly in the browser, bringing a level of interactivity beyond what static HTML
pages offer. Java applets are small, self-contained programs written in the Java programming
language that are designed to be embedded within HTML pages. They run on the client-side,
providing dynamic and interactive content on web browsers. Java applets are executed within a
Java Virtual Machine (JVM), enabling platform independence and security features.

Brief History: Java applets were introduced by Sun Microsystems in the mid-1990s as a
revolutionary approach to web development. At that time, the web was primarily static, and Java
applets allowed developers to bring dynamic, interactive, and multimedia-rich content to web
pages. The "Write Once, Run Anywhere" (WORA) principle of Java, enabled by the JVM,
played a significant role in the initial popularity of Java applets.

1.1.1. Two Types of Applets:


There are two varieties of applets. The first are those based directly on the Applet class. These
applets use the Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no
GUI at all). This style of applet has been available since Java was first created. The second type
of applets is those based on the Swing class JApplet. Swing applets use the Swing classes to
provide the GUI. Swing offers a richer and often easier-to-use user interface than does the AWT.
Thus, Swing-based applets are now the most popular. JApplet inherits Applet, all the features of
Applet are also available in Japplet.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


Key Features of Java Applets:

 Platform Independence: Like all Java programs, applets are platform-independent,


meaning they can run on any device with a Java Virtual Machine (JVM) installed,
regardless of the underlying operating system.
 Security: Applets run in a sandboxed environment within the browser, limiting their
access to the local system. This provides a level of security to prevent malicious
activities.
 Rich User Interface: Java Applets can offer a more sophisticated user interface
compared to traditional web pages. They can handle user input, display graphics, and
respond to events such as mouse clicks or keyboard input.
 Network Communication: Applets can communicate with servers over the network,
enabling them to fetch data or send updates to the server without requiring a full page
reload.

Purpose of java applet

 Interactive Web Content: Applets were initially created to bring interactivity and
dynamic content to web browsers.

 Rich Multimedia Experience: They allowed for the incorporation of graphics,


animations, and other multimedia elements.

 Platform Independence: Java's "Write Once, Run Anywhere" principle allowed applets
to run on various platforms with a JVM.

 Provide dynamic and graphical features on web pages.

 Extend the functionality of a web browser.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


1.1.2. Hierarchy of a java applet

1.1.3. The life cycle of a Java applet

1. Initialization (init() method): The init() method is the first method called when an
applet is loaded. It is used for one-time initialization tasks, such as setting up graphical
components, initializing variables, or loading resources. The init () method is called only
once during the applet's lifetime.
3 2. Starting (start() method): The start() method is called after the init() method and
whenever the user revisits a page containing the applet or interacts with the applet in

Complied By: Misgana.B (MSC) | misge1200@gmail.com


some way. It is used to start any threads or animations, resume paused activities, or
generally prepare the applet for user interaction.
3. Running (User Interaction): The applet is in the running state when the user is
interacting with it. This is the active phase where the applet performs its main tasks based
on user input. During this phase, the applet continuously processes user events, like
mouse clicks or key presses, and updates its display accordingly.
4. paint (Graphics g): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution of start() method and
whenever the applet or browser is resized.
5. Stopping (stop() method): The stop() method is called when the applet is no longer in
focus, either because the user has navigated away from the page or another window has
covered the applet. It is used to pause or stop any ongoing processes, such as animations
or threads, to conserve system resources. If the user returns to the applet, the start()
method is called again.
6. Destroying (destroy() method): The destroy() method is called when the applet is about
to be unloaded or removed from the browser. It is used for cleanup operations, such as
releasing resources, closing files or network connections, and generally preparing the
applet for removal from memory. The destroy() method is the last opportunity for the
applet to perform any necessary cleanup.

1.1.4. Execution Environments


The execution environments for Java applets include the

a. AppletViewer
b. Web browsers.
1. Applet Viewer: The AppletViewer is a standalone command-line tool provided by the Java
Development Kit (JDK). It is used for testing and running Java applets without the need for a
web browser.
 Usage
 Developers can use the AppletViewer during the development and testing
4
phases.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 It allows running and debugging applets independently of a web browser
environment.
 Advantages:

 Simplifies the testing process, enabling developers to identify and fix issues in the
applet's logic or user interface.

 Provides a controlled environment for applet execution.

 Disadvantages:

 Limited user experience compared to running applets within web browsers.

 Does not simulate the exact conditions of a web environment.

2. Web Browser: Java applets are primarily designed to be executed within web browsers.
They are embedded into HTML documents and run on the client side, enhancing the
interactivity and visual appeal of web pages.
 Usage:

 Applets are typically deployed on web servers and accessed by users through web
pages.

 Web browsers such as Chrome, Firefox, Safari, and Internet Explorer support the
execution of Java applets.

 Advantages:

 Widespread accessibility as most users have web browsers installed on their


devices.

 Enables the integration of dynamic and interactive content seamlessly into web
pages.

 Disadvantages:
5

 Security restrictions imposed by modern browsers have limited the use of Java
applets.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 Decreased support and deprecation of Java applet functionality in many browsers.

1.1.5. Applet tag


The `<applet>` tag can include various attributes that define the applet's behavior, appearance,
and other properties. Here's a brief explanation of some commonly used attributes:

 Code: Specifies the name of the applet's main class file without the .class extension.
Example: <applet code="MyApplet" width="300" height="200"></applet>
 Width: Specifies the width of the applet in pixels.
Example: <applet code="MyApplet" width="300" height="200"></applet>
 Height: Specifies the height of the applet in pixels.
Example: `<applet code="MyApplet" width="300" height="200"></applet>`
 alt: Specifies alternative text to be displayed if the browser does not support Java or if the
applet fails to load.
Example:<applet code="MyApplet" width="300" height="200"
alt="Java applet is not supported."></applet>
 Name: Provides a name for the applet, which can be used for referencing the applet in
JavaScript or within the HTML document.
Example: <applet code="MyApplet" width="300" height="200"
name="myApplet"></applet>
 Archive: Specifies a comma-separated list of archive files containing classes and
resources required by the applet.
Example: <applet code="MyApplet" width="300" height="200"
archive="myApplet.jar"></applet>
 Align: Specifies the alignment of the applet within the surrounding HTML content (e.g.,
"left," "right," "center").
Example: <applet code="MyApplet" width="300" height="200"
align="center"></applet>
 hspace, vspace: Specifies horizontal and vertical space around the applet, respectively.

6 Example: <applet code="MyApplet" width="300" height="200"


hspace="10" vspace="10"></applet>

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 Param: Allows you to include parameters that will be passed to the applet. Parameters
are specified as nested `<param>` tags within the `<applet>` tag.
Example: By using html file

<applet code="MyApplet" width="300" height="200">

<param name="param1" value="value1">

<param name="param2" value="value2">

</applet>

Example Code: xyz.java:

import java.applet.Applet;
import java.awt.Graphics;
public class xyz extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);}}
Example: xxy.html
<!DOCTYPE html>
<html>
<head>
<title> This is my first program for java applet </title>
</head>
<body>
<applet code="xyz.class" width="300" height="100">
</applet>
</body>

7 </html>
This simple Java Applet displays the text "Hello, World!" on the applet canvas. The paint
method is a standard method in applets used to draw graphics.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 To run a Java applet using the command prompt, follow these steps:
1. Open the command prompt (cmd).
2. Navigate to the desired directory using the cd command. For example:
cd..
cd..
cd program files
cd java
cd jdk1.8.0_92/sample
cd bin
notepad/xyz.java
3. Open Notepad and create a Java applet file named xyz.java. Save it in the local
disk D, creating an "applet" folder, with the file name as xyz.java.
import java.applet.Applet;
import java.awt.Graphics;

public class xyz extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
}
}
4. Compile the Java applet file using the javac command:
Javac d:\applet\xyz.java
5. Open Notepad and create an HTML file named xyz.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello World Applet</title>
</head>
8 <body>
<applet code="xyz.class" width="300" height="100">
</applet>

Complied By: Misgana.B (MSC) | misge1200@gmail.com


</body>
</html>
6. Run the applet using the appletviewer command:
appletviewer d:\applet\xyz.html
These steps assume that you have the Java Development Kit (JDK) installed, and the
javac and appletviewer commands are available in your system's PATH. Also, please
note that the use of Java applets has significantly decreased, and modern web
development typically uses alternative technologies due to security concerns and browser
compatibility issues.

Graphics in Applets

Graphics in Java applets involve the use of the java.awt.Graphics class to draw various shapes,
text, and images on the applet's surface. Here's a brief explanation of the main components
involved in graphics programming within Java applets:

1. java.awt.Graphics Class:
 The Graphics class is a part of the Abstract Window Toolkit (AWT) package in Java.
 It provides methods for drawing on components such as applets, panels, and frames.
 Graphics operations are performed on an instance of the Graphics class, which
represents the drawing context.
2. Drawing Shapes:
 Lines (drawLine): Draws a line between two points.
g.drawLine(x1, y1, x2, y2);
 Rectangles (drawRect, fillRect): Draws or fills a rectangle.
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);
 Ovals (drawOval, fillOval): Draws or fills an oval.

g.drawOval(x, y, width, height);

9 g.fillOval(x, y, width, height);

 Polygons (drawPolygon, fillPolygon): Draws or fills a polygon.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


int[] xPoints = {x1, x2, x3};

int[] yPoints = {y1, y2, y3};

g.drawPolygon(xPoints, yPoints, numPoints);

g.fillPolygon(xPoints, yPoints, numPoints);

3. Drawing Text:

 Text (drawString): Draws a string of text.

g.drawString("Hello, Java!", x, y);

4. Drawing Images: Images (drawImage): Draws an image on the applet.

Image img = getImage(getCodeBase(), "image.jpg");

g.drawImage(img, x, y, this);

5. Colors and Fonts:

 Setting Color (setColor): Sets the drawing color.

g.setColor(Color.RED);

 Setting Font (setFont): Sets the font for text.

Font font = new Font("Arial", Font.BOLD, 16);

g.setFont(font);

Example Code:

import java.applet.Applet;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

public class GraphicsExample extends Applet {


10 public void paint(Graphics g) {

// Drawing shapes

g.setColor(Color.BLUE);

Complied By: Misgana.B (MSC) | misge1200@gmail.com


g.drawRect(20, 20, 100, 50);

g.drawOval(150, 20, 80, 80);

g.drawLine(300, 20, 400, 70);

// Filling shapes

g.setColor(Color.GREEN);

g.fillRect(20, 100, 100, 50);

g.fillOval(150, 100, 80, 80);

// Drawing text

g.setColor(Color.BLACK);

Font font = new Font("Arial", Font.BOLD, 16);

g.setFont(font);

g.drawString("Hello, Java Graphics!", 20, 200);

This applet draws rectangles, ovals, lines, and text, showcasing the basic operations you can
perform using the Graphics class in Java applet graphics programming.

Applet communication

Applet communication involves the exchange of information between Java applets, between
applets and HTML pages, or between applets and the server. There are several mechanisms for
applet communication, and here's a brief explanation of each:

1. Communication Between Applets:


 Shared Variables: Applets can communicate by sharing variables. This
involves declaring a variable in one applet and accessing or modifying it from
another applet. However, synchronization issues may arise, and it's not the
most robust method for communication.
 AppletContext: The `AppletContext` class provides a way for applets in the

11 same context (such as within the same HTML page) to communicate. Applets
can use `getApplet()` method to obtain a reference to another applet and call
its methods.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 JavaScript Communication: Applets can use JavaScript to communicate
with each other. By calling JavaScript functions from Java code, applets can
trigger actions or exchange data.
2. Communication between Applets and HTML Pages:
 Parameter Passing: HTML tags can pass parameters to Java applets. Applets can
retrieve these parameters using the `getParameter()` method. This allows
customization of applet behavior based on values provided in the HTML.
 Applet Context and Document Base: The `AppletContext` class provides
methods to obtain information about the applet's context and document base. This
information can be used to communicate with the HTML page containing the
applet.
 JavaScript Bridge: Applets can use JavaScript to communicate with the HTML
page. The `JSObject` class in the `netscape.javascript` package allows Java
applets to interact with JavaScript functions on the HTML page.
3. Communication Between Applets and the Server:
 URLConnection and Networking: Applets can communicate with a server using the
`URLConnection` class or by using networking classes in Java. This enables applets
to send requests to a server, retrieve data, and update the applet accordingly.
 Remote Method Invocation (RMI): RMI allows applets to invoke methods on
remote objects. It enables communication between an applet and serverside objects,
providing a powerful mechanism for distributed computing.
 Socket Programming: Java applets can use sockets to establish connections and
communicate with servers using standard socket programming techniques.

1.2. Java Applets vs. Java Applications:

While both Java Applets and Java Applications are types of Java programs, they differ in their
purpose, deployment, and environment.

Java Applets:
12
 Deployment: Applets are designed to be embedded within HTML pages and run in web
browsers. They are loaded and executed on the client-side.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


 User Interface: Applets often create graphical user interfaces (GUIs) using the Abstract
Window Toolkit (AWT) or Swing. They are used to enhance the user experience within
a web page.
 Security: Applets run in a restricted environment (sandbox) to prevent malicious
activities. They have limited access to local resources for security reasons.
 Lifecycle Methods: Applets have specific lifecycle methods (e.g., init, start, stop,
destroy) that are automatically invoked by the browser during different stages of the
applet's execution.

Java Applications:

 Deployment: Java Applications are standalone programs that are typically run on the
client's machine or a server. They are not designed to be embedded in web pages.
 User Interface: Applications can have both command-line interfaces (CLI) and
graphical user interfaces (GUI) using AWT, Swing, or JavaFX.
 Security: Applications have more flexibility and can access local resources with fewer
restrictions compared to applets. However, they still follow Java's security model.
 Lifecycle Methods: Java Applications do not have specific lifecycle methods like
applets. They start executing from the main method.

Java Applets Vs Java Application

Parameter Java applet Java Applications:

Execution Run in a web browser. Run as standalone programs.

Deployment Embedded in HTML pages. Executed from the command line or


double-clicked like any other application.

Interaction Provide interactive content Provide full-fledged desktop applications.


on websites.

13 Environment Restricted environment for Run in a more permissive environment


security reasons. with access to system resources.

Complied By: Misgana.B (MSC) | misge1200@gmail.com


Purpose Originally designed for Designed for various purposes, not
enhancing web pages. necessarily tied to web browsers.

14

Complied By: Misgana.B (MSC) | misge1200@gmail.com

You might also like