Thursday, August 29, 2013

Programming in Java: Applets

Applets

Console-based applications constitute only one class of Java programs. Another type of program is the applet. Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document. After an applet arrives on the client, it has limited access to resources so that it can produce a graphical user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

Two Types of Applets

It is important to state at the outset that there are two varieties of applets. The first are those based directly on the Applet class described in this chapter. 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. However, traditional AWT-based applets are still used, especially when only a very simple user interface is required. Thus, both AWT- and Swing-based applets are valid. As JApplet inherits Applet, all the features of Applet are also available in JApplet also.

Applet Basics

All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer. appletviewer is the standard applet viewer provided by the JDK.
Execution of an applet does not begin at main( ). Actually, few applets even have main( )methods. Instead, execution of an applet is started and controlled with an entirely different mechanism
Output to your applet’s window is not performed by System.out.println( ). Rather, in non-Swing applets, output is handled with various AWT methods, such as drawString( ).
Input is also handled differently than in a console application.
To use an applet, it is specified in an HTMLfile. One way to do this is by using the <APPLET> tag.
The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTMLfile. An applet can be viewed and tested more conveniently using the appletviewer, by simply including a comment at the head of our Java source code file that contains the APPLET tag. E.g.
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

The HTML <APPLET> Tag

APPLET tag is used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers will allow many applets on a single page.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional.
< APPLET
         [CODEBASE = codebaseURL]
         CODE = appletFile
         [ALT = alternateText]
         [NAME = appletInstanceName]
         WIDTH = pixels HEIGHT = pixels
         [ALIGN = alignment]
         [VSPACE = pixels] [HSPACE = pixels]
> 

[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
. . .
[HTML Displayed in the absence of Java]
</APPLET>
Let’s take a look at each part now.
CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified.
CODE: CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set.
ALT: The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets.
NAME: NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them.
WIDTH and HEIGHT: WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.
ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE and HSPACE: These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.
PARAM NAME and VALUE: The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

The Applet Class

Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. Following are the major methods defined by Applet class.
Method
Description
void init( )
Called when an applet begins execution. It is the first method called for any applet.
void start( )
Called by the browser when an applet should start (or resume) execution. It is automatically called after init( ) when an applet first begins.
void stop( )
Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start( ).
void destroy( )
Called by the browser just before an applet is terminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction.
void showStatus(String str)
Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place.
void resize(int width, int height)
Resizes the applet according to the dimensions specified by width and height.
boolean isActive( )
Returns true if the applet has been started. It returns false if the applet has been stopped.
String getParameter(String paramName)
Returns the parameter associated with paramName. null is returned if the specified parameter is not found.
URL getCodeBase( )
Returns the URL associated with the invoking applet.
URL getDocumentBase( )
Returns the URL of the HTML document that invokes the applet.
String getAppletInfo( )
Returns a string that describes the applet.

Applet Architecture

An applet is a window-based program. As such, its architecture is different from the console-based programs. The major features of an applet program are:
  • Applets are event driven. An applet waits until an event occurs. The run-time system notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return. Any applet should not enter a mode of operation in which it maintains control for an extended period.
  •  The user initiates interaction with an applet. In console-based program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked event is generated.

Applet Skeleton

Most applets override a set of methods that provides the basic mechanism by which the browser or applet viewer controls the execution of the applet. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use.
AWT-based applets will also override the paint( ) method, which is defined by the AWT Component class. This method is called when the applet’s output must be redisplayed. These five methods can be assembled into the skeleton shown here:
FirstApplet.java
import java.awt.*;
import java.applet.*;
/*
<applet code="FirstApplet" width=300 height=100>
</applet>
*/
public class FirstApplet extends Applet {
         /* Called first. */
         public void init() {
                  // initialization
         }
         /* Called second, after init(). Also called whenever the applet is restarted. */
         public void start() {
                  // start or resume execution
         }
         /* Called when the applet is stopped. */
         public void stop() {
                  // suspends execution
         }
         /* Called when applet is terminated. This is the last method executed. */
         public void destroy() {
                  // perform shutdown activities
         }
         /* Called when an applet's window must be restored. */
         public void paint(Graphics g) {
                  // redisplay contents of window
         }
}
This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical user interface. The second import statement imports the applet package, which contains the class Applet.
The <applet> tag given as comment is used by the applet viewer to display the applet.
Every applet that you create must be a subclass of Applet. So we define the class FirstApplet as a subclass of Applet. This class must be declared as public, because it will be accessed by code that is outside the program.
The above applet can be compiled as:
>javac FirstApplet.java
It can be run using applet viewer as
> appletviewer FirstApplet.java

The skeleton applet above does nothing, but displays the following applet.


Applet initialization and termination

It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the following methods are called, in this sequence:
  1. init( )
  2. start( )
  3. paint( )

When an applet is terminated, the following sequence of method calls takes place:
  1. stop( )
  2. destroy( )

Let’s look more closely at these methods.

init( )

The init( ) method is the first method to be called. This is where we should initialize variables. This method is called only once during the life time of our applet.

start( )

The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once, the first time an applet is loaded; start( ) is called each time an applet’s HTML document is displayed on the screen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( )

The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may go behind 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. This context is used whenever output to the applet is required.

stop( )

The stop( ) method is called when a web browser leaves the HTML document containing the applet; E.g. when it goes to another page. When stop( ) is called, the applet is probably running. It suspend threads that don’t need to run when the applet is not visible. It can be restarted them when start( ) is called if the user returns to the page.

destroy( )

The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point all resources the applet was using must be freed. The stop( ) method is always called before destroy( ).
The life cycle of a typical applet can be depicted as shown below:


Simple Applet Display Methods

To display a string in an applet window we can use drawString( ) method, which is a member of the Graphics class. Typically, it is called from within either update( ) or paint( ).
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).
To set the background colour of an applet’s window the setBackground( ) method can be used. To set the foreground colour (e.g. the color in which text is shown), the setForeground( ) method can be used.
These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
Here, newColor specifies the new colour.
Example:
setBackground(Color.green);
setForeground(Color.red);
The constants that can be used to specify colors, defined by the class Color are: Color.black, Color.magenta, Color.blue, Color.orange, Color.cyan, Color.pink, Color.darkGray, Color.red, Color.gray, Color.white, Color.green, Color.yellow, Color.lightGray
The background and fore ground colours can be changes any where according to the requirement, but a good place to do them is in the init() method.
the current settings for the background and foreground colours can be obtained by calling getBackground( ) and getForeground( ), respectively. They are also defined by Component. The signatures of the methods are as shown:
Color getBackground( )
Color getForeground( )

Requesting Repainting

An applet writes to its window only when its update( ) or paint( ) method is called by the AWT. One of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT.
AWT defines the repaint( ) method to solve this issue. It causes the AWT run-time system to execute a call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ).
Two simple forms of repaint() are:
void repaint( )
which causes the entire window to be repainted and
void repaint(int left, int top, int width, int height)
which paints only the region specified by the arguments. This saves time, as painting the entire window is costly in terms of time.

Using the Status Window

In addition to displaying information in its window, an applet can also display a message to the status window of the browser or applet viewer on which it is running. To do so, the showStatus( ) method can be called passing the string to be displayed as an argument. It can be used for giving updates to user regarding what is happening, suggest options, report errors and for debugging.
The signature of the method is:
void showStatus(String message)
Example:
showStatus("This is the status window");

Passing Parameters to Applets

The <APPLET> tag in HTML allows us to pass parameters to our applet. To retrieve a parameter, the getParameter( ) method can be used. It returns the value of the specified parameter in the form of a String object.
Example: The following program demonstrates how parameters can be passed into an applet
/* <applet code = "AppletParam" height = "300" width = "500">
<param name = "Language" value ="Java">
<param name = "Creators" value ="Sun">
</applet>*/
import java.awt.*;
import java.applet.*;

public class AppletParam extends Applet{
public void init(){
setBackground(Color.white);
setForeground(Color.red);
}
public void paint(Graphics g){
String p1 = getParameter("Language");
String p2 = getParameter("Sun");
g.drawString("Language: "+p1,25, 75);
g.drawString("Creators: "+p2,25, 100);

}
}

The above program creates the following applet as the output


No comments:

Post a Comment