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

Java Applets

Java applets are small applications written in Java that run within a web page, often as plug-ins. The document details the components and life cycle of applets, including methods for creating user interface elements like buttons, labels, and text fields, as well as the applet's life cycle methods such as init(), start(), and paint(). It also discusses how to embed applets in HTML and their applications in providing interactive features on web pages.

Uploaded by

aashiyan.shaan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Applets

Java applets are small applications written in Java that run within a web page, often as plug-ins. The document details the components and life cycle of applets, including methods for creating user interface elements like buttons, labels, and text fields, as well as the applet's life cycle methods such as init(), start(), and paint(). It also discusses how to embed applets in HTML and their applications in providing interactive features on web pages.

Uploaded by

aashiyan.shaan
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

JAVA APPLETS

In computing, an applet is any small application that performs one specific task that runs
within the scope of a larger program, often as a plug-in The term is frequently used to
refer to a Java applet, a program written in the Java programming language that is
designed to be placed on a web page. The word applet was first used in 1990 in PC
Magazine.

Components and Containers

Containers
Elements that may "contain" other elements inside of them. One
container may have another container inside. Panels are containers.

Panels
are containers therefore we may add elements to them. We can add a
variety of elements such as buttons, labels, etc. Panels allow us to
format the screen. Panels must have a specific layout. If a layout is not
specified, the default will be a FlowLayout.

There are several kinds of layouts. In this class we will cover three:
FlowLayout, BorderLayout and GridLayout.

 FlowLayout Adds components to the screen one after another


from top to bottom and from left to right. Components are
rearrange when the user resizes the window. FlowLayout may
take no arguments.
Constructor: FlowLayout fl = new FlowLayout( );
 BorderLayout Divides the screen in nine sections based in
geographic orientation such as "North", "South", "East"....etc.
BorderLayout takes no arguments.
Constructor: BorderLayout bl = new BorderLayout( );
 GridLayout Divides the screen in the number of sections
specified by the programmer. GridLayout takes 2 arguments
(#rows, #cols).
Constructor: GridLayout gl = new GridLayout(rows, cols ); //rows
and cols are int numbers

Button
Constructors:
Button myButton = new Button("button's caption");
.setBackground(Color.color); //argument as in Color class
.setFont(type, style, size); //argument as in Font class
The size of the button depends on the screen layout.
Example, adding a button to the screen:
add(new Button("thisButton");
It could also be done as:
Button b = new Button("thisButton");
add(b);

Label
Constructors:
Label myLabel = new Label("label's caption");
A Label is basically a String drawn in the Panel. The effect is the same
as using DrawString in a Canvas or straight in the screen itself.
Example, adding a label to the screen:

add(new Label("thisLabel");
it could also be done as:
Label label = new Label("thisLabel");
add(label);

TextFields
Constructors:

 TextField tf1 = new TextField(int characters);


 TextField tf2 = new TextField(String caption);

TextFields are used to get information entered by the user.


The .getText method is used for this purpose.
TextField TextFieldObject= new TextField(20);
String s = "";
s = TextFieldObject.getText( );
//now the user input is in s

You may also display information in a TextField: The .setText method is


used for this purpose.
TextField TextFieldObject= new TextField(20);
String s = "hello";
TextFieldObject.setText(s );

TextFields can be editable or non-editable depending on their use. If


we want to read information from the user through a Textfield it should
be editable. If we want to use the TextField to display information to
the user then they should non editable to avoid the user modifying it.
The TextField is by default editable and to make non-editable we do
the following:

TextFieldObject.setEditable(false);
to make it editable again:

TextFieldObject.setEditable(true);

TextAreas
These components are just like the TextFields but they can hold
several lines of characters, while the TextField may hold only one line.
Constructors:

 TextArea ta = new TextArea (int #rows, int #columns);


 TextArea ta = new TextArea (String s);
 TextArea ta = new TextArea (String s, int #rows, int #columns);

The setText(String ), SetEditable (boolean) and getText( ) are just the


same as in TextFields. However there is an extra method for
TextAreas:

ta.append( String ); This will append the specified text to the


Text that is already in the TextArea.

Choices
A choice is basically a pull-down list of options available for the user to
select from.
Constructor:

 Choice c = new Choice( );

To add choices/options to the Choice object:


c.add (String sChoice); //repeat this as many times as needed
To see what the user selected, there are two useful methods:
c.getSelectedIndex( ); //returns an int that represents the
position
//of the selected choice
c.getSelectedItem( ); // returns the String chosen by the user

Adding components to the screen:

add(component)
Which can also be:
add(container)
if you want to add a container inside another.
Life Cycle of an Applet:

Various states, an applet, undergoes between its object creation and object removal (when
the job is over) is known as life cycle. Each state is represented by a method. There exists
5 states represented by 5 methods. That is, in its life of execution, the applet exists (lives)
in one of these 5 states.

These methods are known as "callback methods" as they are called automatically by the
browser whenever required for the smooth execution of the applet. Programmer just write
the methods with some code but never calls.

Following are the methods.

1. init() method
2. start() method
3. paint() method
4. stop() method
5. destroy() method

These methods are known as life cycle methods. These methods are defined in
java.applet.Applet class except paint() method. The paint() method is defined in
java.awt.Component class, an indirect super class of Applet.

Browser Responsibilities

The life cycle methods are called as callback methods as they are called implicitly by
the browser for the smooth execution of the applet. Browser should provide an
environment known as container for the execution of the applet. Following are the
responsibilities of the browser.

1. It should call the callback methods at appropriate times for the smooth execution
of the applet.
2. It is responsible to maintain the life cycle of the applet.
3. It should have the capability to communicate between applets, applet to
JavaScript and HTML, applet to browser etc.

Description of Life Cycle methods

Even though, the methods are called automatically by the browser, the programmer
should know well when they are called and what he can do with the methods. Following
is the schematic representation of the methods.
Brief Description of Life Cycle Methods

Following is the brief description of the above methods.

1. init(): The applet's voyage starts here. In this method, the applet object is created
by the browser. Because this method is called before all the other methods,
programmer can utilize this method to instantiate objects, initialize variables,
setting background and foreground colors in GUI etc.; the place of a constructor
in an application. It is equivalent to born state of a thread.
2. start(): In init() method, even through applet object is created, it is in inactive
state. An inactive applet is not eligible for microprocessor time even though the
microprocessor is idle. To make the applet active, the init() method calls start()
method. In start() method, applet becomes active and thereby eligible for
processor time.
3. paint(): This method takes a java.awt.Graphics object as parameter. This class
includes many methods of drawing necessary to draw on the applet window. This
is the place where the programmer can write his code of what he expects from
applet like animation etc. This is equivalent to runnable state of thread.
4. stop(): In this method the applet becomes temporarily inactive. An applet can
come any number of times into this method in its life cycle and can go back to the
active state (paint() method) whenever would like. It is the best place to have
cleanup code. It is equivalent to the blocked state of the thread.
5. destroy(): This method is called just before an applet object is garbage collected.
This is the end of the life cycle of applet. It is the best place to have cleanup code.
It is equivalent to the dead state of the thread.
After knowing the methods, let us know when they are called by the browser.

 init() method is called at the time of starting the execution. This is called only
once in the life cycle.
 start() method is called by the init() method. This method is called a number of
times in the life cycle; whenever the applet is deiconifed , to make the applet
active.
 paint() method is called by the start() method. This is called number of times in
the execution.
 stop() method is called whenever the applet window is iconified to inactivate the
applet. This method is called number of times in the execution.
 destroy() method is called when the applet is closed. This method is called only
once in the life cycle.

Observe, the init() and destroy() methods are called only once in the life cycle. But,
start(), paint() and stop() methods are called a number of times.

- See more at: http://way2java.com/applets/life-cycle-of-applet/#sthash.2ooDkj2v.dpuf

HTML for Applet

We cannot open an applet directly in a browser, even though, the browser is meant to
execute an applet. For every applet, a HTML file is to be written in which we give the
name and address etc. of the applet.

Following is the example code for embedding applet in a HTML file.

1 <applet code = "LifeTest.class" width = "250" height = "200">


2 </applet>

The <applet> tag comes with many attributes of which code, width and height are
important. The other, optional, we discuss later. The code attribute includes the name of
the applet. width and height attributes give the size of applet window in the browser, in
pixels.

- See more at: http://way2java.com/applets/life-cycle-of-applet/#sthash.2ooDkj2v.dpuf

update() Method
To eliminate flashing, you must override the update() method. The reason lies in the
way the AWT requests that a Component (such as an Applet, Canvas, or Frame) repaint
itself.
The AWT requests a repaint by calling the Component's update() method. The default
implementation of update() clears the Component's background before calling paint().
Because eliminating flashing requires that you eliminate all unnecessary drawing, your
first step is always to override update() so that it clears the entire background only when
necessary. When moving drawing code from the paint() method to update(), you
might need to modify the drawing code so that it doesn't depend on the background being
cleared.

Note: Even if your implementation of update() doesn't call paint(), you must still
implement a paint() method. The reason: When an area that your Component displays
is suddenly revealed after being hidden (behind another window, for example), the AWT
calls paint() directly, without calling update(). An easy way to implement paint() is
to simply have it call update().

Here is the code for a modified version of the previous example that implements
update() to eliminate flashing. Here is the applet in action:

Here's the new version of the paint() method, along with the new update() method.
All of the drawing code that used to be in the paint() method is now in the update()
method. Significant changes in the drawing code are in bold font.

public void paint(Graphics g) {


update(g);
}

public void update(Graphics g) {


Color bg = getBackground();
Color fg = getForeground();

...//same as old paint() method until we draw the rectangle:


if (fillSquare) {
g.fillRect(x, y, w, h);
fillSquare = false;
} else {
g.setColor(bg);
g.fillRect(x, y, w, h);
g.setColor(fg);
fillSquare = true;
}
...//same as old paint() method
}
Note that since the background is no longer automatically cleared, the drawing code must
now draw the non-black rectangles, as well as the black ones.
Passing Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the
opening and closing APPLET tags. Inside the applet, you read the values passed through
the PARAM tags with the getParameter() method of the java.applet.Applet class.

The program below demonstrates this with a generic string drawing applet. The applet
parameter "Message" is the string to be drawn.

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

public class DrawStringApplet extends Applet {

private String defaultMessage = "Hello!";

public void paint(Graphics g) {

String inputFromPage = this.getParameter("Message");


if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 25);

You also need an HTML file that references your applet. The following simple HTML
file will do:

<HTML>
<HEAD>
<TITLE> Draw String </TITLE>
</HEAD>

<BODY>
This is the applet:<P>
<APPLET code="DrawStringApplet" width="300" height="50">
<PARAM name="Message" value="Howdy, there!">
This page will be very boring if your
browser doesn't understand Java.
</APPLET>
</BODY>
</HTML>

Of course you are free to change "Howdy, there!" to a "message" of your choice. You
only need to change the HTML, not the Java source code. PARAMs let you customize
applets without changing or recompiling the code.
This applet is very similar to the HelloWorldApplet. However rather than hardcoding the
message to be printed it's read into the variable inputFromPage from a PARAM element in
the HTML.

You pass getParameter() a string that names the parameter you want. This string
should match the name of a PARAM element in the HTML page. getParameter() returns
the value of the parameter. All values are passed as strings. If you want to get another
type like an integer, then you'll need to pass it as a string and convert it to the type you
really want.

The PARAM element is also straightforward. It occurs between <APPLET> and </APPLET>.
It has two attributes of its own, NAME and VALUE. NAME identifies which PARAM this is.
VALUE is the string value of the PARAM. Both should be enclosed in double quote marks if
they contain white space.

An applet is not limited to one PARAM. You can pass as many named PARAMs to an
applet as you like. An applet does not necessarily need to use all the PARAMs that are in
the HTML. Additional PARAMs can be safely ignored.

Applications of Applets

Provided that an applet is hosted by an operating system, it can function as any other
normal software application but performs only a small set of tasks. Examples of
applications often classified as applets are all of the accessories bundled in Microsoft
Windows (such as Windows Notepad or Microsoft Paint). Applets are not full-featured
application programs, and are intended to be easily accessible.

Applet as an extension of other software

In some cases, an applet does not run independently. These applets must run either in a
container provided by a host program, through a plugin, or a variety of other applications
including mobile devices that support the applet programming model.

Web-based Applets

Applets are used to provide interactive features to web applications that cannot be
provided by HTML alone. They can capture mouse input and also have controls like
buttons or check boxes. In response to the user action an applet can change the provided
graphic content. This makes applets well suitable for demonstration, visualization, and
teaching. There are online applet collections for studying various subjects, from physics
to heart physiology.Applets are also used to create online game collections that allow
players to compete against live opponents in real-time.
An applet can also be a text area only, providing, for instance, a cross platform
command-line interface to some remote system. If needed, an applet can leave the
dedicated area and run as a separate window. However, applets have very little control
over web page content outside the applet dedicated area, so they are less useful for
improving the site appearance in general (while applets like news tickers or WYSIWYG
editors are also known). Applets can also play media in formats that are not natively
supported by the browser

HTML pages may embed parameters that are passed to the applet. Hence the same applet
may appear differently depending on the parameters that were passed.

Examples of Web-based Applets include:

 QuickTime movies
 Flash movies
 Windows Media Player applets, used to display embedded video files in Internet
Explorer (and other browsers that support the plugin)
 3D modeling display applets, used to rotate and zoom a model
 Browser games can be applet-based, though some may develop into fully
functional applications that require installation.

Applet vs. Subroutine

A larger application distinguishes its applets through several features:

Applets execute only on the "client" platform environment of a system, as contrasted


from "servlet". As such, an applet provides functionality or performance beyond the
default capabilities of its container (the browser).

 The container restricts applets' capabilities.


 Applets are written in a language different from the scripting or HTML language
that invokes it. The applet is written in a compiled language, whereas the scripting
language of the container is an interpreted language, hence the greater
performance or functionality of the applet. Unlike a "subroutine", a complete web
component can be implemented as an applet.

Java Applet
Main article: Java Applet

Java Applets can provide web applications with interactive features that cannot be
provided by HTML. Since Java's bytecode is platform-independent, Java applets can be
executed by browsers running under many platforms, including Windows, Unix, Mac
OS, and Linux. When a Java technology-enabled web browser processes a page that
contains an applet, the applet's code is transferred to the client's system and executed by
the browser's Java Virtual Machine (JVM). An HTML page references an applet either
via the deprecated <APPLET> tag or via its replacement, the <OBJECT> tag.
Security

Recent developments in the coding of applications including mobile and embedded


systems have led to the awareness of the security of applets.

Open Platform Applets

Applets in an open platform environment should provide secure interactions between


different applications. A compositional approach can be used to provide security for open
platform applets.Advanced compositional verification methods have been developed for
secure applet interactions.

Java Applets

A Java applet contains different security models: unsigned Java applet security, signed
Java applet security, and self signed Java applet security.

Web-based Applets

In an applet-enabled web browser, many methods can be used to provide applet security
for malicious applets. A malicious applet can infect a computer system in many ways,
including denial of service, invasion of privacy, and annoyance.A typical solution for
malicious applets is to make the web browser to monitor applets' activities. This will
result in a web browser that will enable the manual or automatic stopping of malicious
applets. To illustrate this method, AppletGuard was used to observe and control any
applet in a browser successfully.

You might also like