Unit II: Applet as Java Applications – Java Programming - BCA Notes (Pokhara University)

Breaking

Sunday, July 19, 2020

Unit II: Applet as Java Applications – Java Programming

Introduction to Java Applet:

An applet is a java program that runs in a web browser. An applet is a container class like a frame. An applet is a java class that extends the java.applet.Applet class. Applets are designed to be embedded within the HTML page. Whenever a user views an HTML page that contains an applet, the code for the applet is downloaded to the user machine. A JVM is required to view an applet. The JVM on the user machine creates an instance of the applet and invokes various methods during the applet lifetime.

Applet As Java Applications, Introduction To Application, Lifecycle Of Applets, Applets Methods, Applet Vs Applications, Application Conversion To Applets

In order to create a java applet we have to import a package called an applet.Applet, for example:

import java.applet.Applet;

public class MyApplet extends Applet{

      statements;

}

<applet code = “MyApplet.class” height = 300 width = 300></applet>

Save this file as: MyApplet.html or MyApplet.txt or We can write the applet code in the java file as well but should provide in a comment section as below:

//<applet code = “MyApplet.class” height = 300 width = 300></applet>

import java.applet.Applet;

public class MyApplet extends Applet{

      statements;

}

JVM on the user, the machine creates an instance of the applet class and invokes various methods during the applet lifetime.

Creating an Applet:

import java.awt.*;

import java.applet.Applet;

public class DemoApplet extends Applet{

      public void paint (Graphics g){

            g.drawString("First Applet Program",80,40);

      }

}

In order to run this java applet program, we must create a file that should contain a tag called <applet></applet> as mention below:

1. <applet code = “DemoApplet.class” height = 300 width = 300></applet>

2. File should be saved as DemoApplet.html or DemoApplet.txt

3. To run the program, we have a tag called appletviewer such as appletviewer DemoApplet.html or appletviewer DemoApplet.txt.

Introduction to Java Application:

An application is a stand-alone java program that runs with the support of a virtual machine in a client or server-side. A java application is designed to perform a specific function to run on any Java-compatible virtual machine regardless of the computer architecture. An application is either executed for the user or for some other application program.

Examples of java applications include database programs, development tools, word processors, text and image editing programs, spreadsheets, web browsers, etc.

Example:

public class Demo {

   public static void main(String args[]) {

      System.out.println(“Welcome to BCA Notes Pokhara University”);

   }

}


Difference between Applet and Application:

Applet

Application

Small Program

Large Program

Used to run a program on client browser

Can be executed on a standalone computer system

Applet is portable and can be executed by any Java supported browser.

Need JDK, JRE, JVM installed on client machine.

Applet applications are executed in a restricted environment.

Application can access all the resources of the computer.

Applets are created by extending the java.applet.Applet

Applications are created by writing public static void main (String [] s) method.

Applet application has 5 methods which will be automatically invoked on occurrence of specific event.

Application has a single start point which is main method.

Example:

import java.awt.*;

import java.applet.*;

public class Myclass extends Applet {

  public void init() { }

  public void start() { }

  public void stop() {}

  public void destroy() {}

  public void paint(Graphics g) {}

}

Example:

public class MyClass {

  public static void main(String args[]) {}

}


Life Cycle of Applets:

Java applet inherits features from the class Applet. Thus, whenever an applet is created, it undergoes a series of changes from initialization to destruction. Various stages of an applet life cycle are depicted in the figure below:

Applet As Java Applications, Introduction To Application, Lifecycle Of Applets, Applets Methods, Applet Vs Applications, Application Conversion To Applets

1. Initial State:

When a new applet is born or created, it is activated by calling init() method. At this stage, new objects to the applet are created, initial values are set, images are loaded and the colors of the images are set. An applet is initialized only once in its lifetime. It's general form is:

public void init( ) {

//Action to be performed

}

2. Running State:

An applet achieves the running state when the system calls the start () method. This occurs as soon as the applet is initialized. An applet may also start when it is in idle state. At that time, the start () method is overridden. It's general form is:

public void start( ) {

//Action to be performed

}

3. Idle State:

An applet comes in an idle state when its execution has been stopped either implicitly or explicitly. An applet is implicitly stopped when we leave the page containing the currently running applet. An applet is explicitly stopped when we call stop () method to stop its execution. It's general form is:

public void stope

{

//Action to be performed

}

4. Dead State:

An applet is in dead state when it has been removed from the memory. This can be done by using destroy () method. It's general form is:

public void destroy( ) {

//Action to be performed

}


Methods of Applet Class:

Applet As Java Applications, Introduction To Application, Lifecycle Of Applets, Applets Methods, Applet Vs Applications, Application Conversion To Applets

1. void init()

This method is called once by the browser or applet viewer when the applet that it has been loaded into the system. It performs the initialization of an applet. Typical examples are the initialization of instance variables and GUI components of the applet.

2. void start()

This method is called after the init method completes execution and every time the user of the browser returns to the HTML on which the applet resides (after browsing to another HTML page). Typical actions include starting an animation or other execution threads.

3. void paint(Graphics g)

This method is called automatically every time the applet needs to be repainted. For example, if the user of the browser covers the applet with another open window on the screen, then uncovers the applet, the paint method is called. (Inherited from Container)

4. void stop()

This method is called by the browser or applet viewer when the applet should stop its execution, normally when the user of the browser leaves the HTML page on which the applet resides. Typical actions performed here are to stop execution of animation and threads.

5. void destroy()

This method is called by the browser or applet viewer when the applet is being removed from memory, normally when the user of the browser exits the browsing session. This method performs any tasks that are required to destroy any resources that it has allocated.

Every Applet needs to implement one or more of the init(), start( ) and paint( ) methods. At the end of the execution, stop( ) method is invoked, followed by destroy( ) method to deallocate the applet’s resources. Besides these methods, there are many more methods. They are;

Methods

Description

AppletContext getAppletContext( )

Returns the context associated with the applet.

String getAppletInfo( )

Returns a string that describes the applet.

AudioClip getAudioClip(URL url)

Returns an AudioClip object that encapsulates the audio clip found at the location specified by url.

AudioClip getAudioClip(URL url,

String clipName)

Returns an AudioClip object that encapsulates the audio clip found at the location specified by url and having the name specified by clipName.

URL getCodeBase( )

Returns the URL associated with the invoking applet.

URL getDocumentBase( )

Returns the URL of the HTML document that invokes the applet.

Image getImage(URL url)

Returns an Image object that encapsulates the image found at the location specified by url.

Image getImage(URL url,

String imageName)

Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName.

String getParameter(String paramName)

Returns the parameter associated with paramName. Null is returned if the specified parameter is not found.

String[ ] [ ] getParameterInfo( )

Returns a String table that describes the parameters recognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose.

void init( )

Called when an applet begins execution. It is the first method called for any applet.

boolean isActive( )

Returns true if the applet has been started. It returns false if the applet has been stopped.

static final AudioClip

newAudioClip(URL url)

Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. This method is similar to getAudioClip( ) except that it is static and can be executed without the need for an Applet object.

void play(URL url)

If an audio clip is found at the location specified by url, the clip is played.

void play(URL url, String clipName)

If an audio clip is found at the location specified by url with the name specified by clipName, the clip is played.

void resize(Dimension dim)

Resizes the applet according to the dimensions specified by dim. Dimension is a class stored inside java.awt. It contains two integer fields: width and height.

void resize(int width, int height)

Resizes the applet according to the dimensions specified by width and height.

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 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 the execution of the applet. Once stopped, an applet is restarted when the browser calls start( ).


Application Conversion to Applets:

It is easy to convert a graphical Java application (i.e. an application that uses the AWT and that we can start with the java program launcher) into an applet that we can embed it on a web page. 

Applet As Java Applications, Introduction To Application, Lifecycle Of Applets, Applets Methods, Applet Vs Applications, Application Conversion To Applets

Here are the specific steps for converting an application to an applet:

1. Make an HTML page with the appropriate tag to load the applet code.

2. Extend the JApplet (Applet) class. Make this class public. Otherwise, the applet cannot be loaded.

3. Eliminate the main method in the application. Do not construct a frame window for the application. Our application will be displayed inside the browser.

4. Move any initialization code from the frame window constructor to the init() method of the applet. We don't need to explicitly construct the applet object. The browser instantiates it and calls the init() method.

5. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.

6. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.

7. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (We can title the web page using the HTML title tag.)

8. Don't call setVisible(true). The applet is displayed automatically.

A Program To Demonstrate The Use Of Init() Method And Start() Method:

import java.awt.*;

import java.applet.*;

/*

<applet code="Sample" width=300 height=50>

</applet>

*/

public class Sample extends Applet{

String msg;

// set the foreground and background colors.

public void init() {

setBackground(Color.green);

setForeground(Color.red);

msg = "Inside init( ) --";

}

// Initialize the string to be displayed.

public void start() {

msg += " Inside start( ) --";

}

// Display msg in applet window.

public void paint(Graphics g) {

msg += " Inside paint( ).";

g.drawString(msg, 10, 30);

}

}


Event Handling in Applet:

import java.applet.*; 

import java.awt.*; 

import java.awt.event.*;

//<applet code = "EventApplet.java" height = 300 width = 300></applet>

 

public class EventApplet extends Applet implements ActionListener{ 

Button b; 

TextField tf; 

public void init(){ 

tf=new TextField(); 

tf.setBounds(30,40,150,20); 

b=new Button("Click"); 

b.setBounds(80,150,60,50); 

add(b);

add(tf); 

b.addActionListener(this); 

setLayout(null); 

 public void actionPerformed(ActionEvent e){ 

      tf.setText("Welcome"); 

 }  

}


Images in Applets:

Applets can be used to browse and draw images and animations. To draw the images, the java.awt.Graphics class comes with a method drawImage(). With the help of this method and ImageObserver in the background, images can be drawn on the applet window.

 

Example:

import java.awt.*;

import java.applet.*;

import java.net.*;

public class ImageWithApplet extends Applet

{

public void paint( Graphics g )

{

URL url1 = getCodeBase();

Image img = getImage(url1, "image.gif");

g.drawImage(img, 60, 120, this);

}

}

 

HTML File To Run The Above Applet – Imagewithapplet.Html

<applet code="ImageWithApplet.class" width="350" height="350"></applet>


Playing Audio in Applet:

An applet can play an audio file represented by the AudioClip interface in the java.applet package. The AudioClip interface has three methods, including:

1. public void play(): Plays the audio clip one time, from the beginning.

2. public void loop(): Causes the audio clip to replay continually.

3. public void stop(): Stops playing the audio clip.

To obtain an AudioClip object, we must invoke the getAudioClip() method of the Applet class. The getAudioClip() method returns immediately, whether or not the URL resolves to an actual audio file. The audio file is not downloaded until an attempt is made to play the audio clip.

Following Example Shows All The Steps To Play An Audio:

import java.applet.*;

import java.awt.*;

import java.net.*;

/*

<applet code="AudioDemo.class" width="0" height="0">

<param name="audio" value="test.wav">

</applet>

*/

public class AudioDemo extends Applet

{

private AudioClip clip;

private AppletContext context;

public void init()

{

context = this.getAppletContext();

String audioURL = this.getParameter("audio");

if(audioURL == null)

{

audioURL = "default.au";

}

try

{

URL url = new URL(this.getDocumentBase(), audioURL);

clip = context.getAudioClip(url);

}catch(MalformedURLException e)

{

e.printStackTrace();

context.showStatus("Could not load audio file!");

}

}

public void start()

{

if(clip != null)

{

clip.loop();

}

}

public void stop()

{

if(clip != null)

{

clip.stop();

}

}

}

No comments:

Post a Comment

If you have any doubt, then don't hesitate to drop comments.