logo

Java Applet Basics


Show

An Applet is a Java plan that sprints in a Web browser. An applet could be a completely practical Java application since it has the whole Java API at its discarding.

There are a number of vital disparities between an applet and an impartial Java application, counting the subsequent −

  • An applet is a Java group that expands the java.applet.Applet set.
  • A main() way is not to appeal on an applet, and an applet set will not name the main().
  • Applets are intended to be implanted inside an HTML page.
  • while a user sights an HTML page that holds an applet, the policy for the applet is downloaded to the user's machine.
  • A JVM is necessitated to view an applet. The JVM can be a plug-in either of the Web browser or a disconnect runtime situation.
  • The JVM on the utilizer's mechanism develops a case of the applet class and invokes a variety of methods through the applet's life.
  • Applets have severe safety rules that are imposed by the Web browser. The refuge of an applet is habitually submitted to as sandbox refuge, comparing the applet to a child playing in a sandbox with various rules that must be followed.
  • Additional classes that the applet requires can be downloaded in a solitary Java Archive (JAR) file.

Life Cycle of an Applet

Four processes in the Applet class presents you the scaffold on which you construct any grave applet −

  • init − This technique is meant for whatever initialization is required for your applet. It is described after the paragraph tags within the applet tag have been procedures.
  • start − This technique is mechanically called following the browser calls the init process. It is also called when the user revisits the page enclosing the applet following having disappeared off to other pages.
  • stop − This process is robotically called while the user budges off the page on which the applet assembles. It can be called frequently in a similar applet.
  • destroy − This system is only identified when the browser closes on the whole. Since applets are predestined to exist on an HTML page, you should not usually leave reserves after a consumer leaves the page that encloses the applet.
  • Paint − Invoked right away after the start() technique, and also any time the applet requires to renovate itself in the browser. The paint() technique is really inherited from the java.awt.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java:

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

public class HelloWorldApplet extends Applet {
   public void paint (Graphics g) {
      g.drawString ("Hello World", 25, 50);
   }
}

These import statements bring the classes into the scope of our applet class:

  • java.applet.Applet
  • java.awt.Graphics

With no, import reports, the Java compiler would not know the group's Applet and Graphics, which the applet group refers to.

The Applet Class

Each applet is a conservatory of the java.applet.Applet class. The foot Applet class presents systems that an obtained Applet class might call to acquire row and services from the browser situation.

These comprise methods that do the following:

These comprise methods that do the following:

  • Get applet parameters
  • Get the network location of the HTML file that contains the applet
  • Get the network location of the applet class directory
  • Print a status message in the browser
  • Fetch an image
  • Fetch an audio clip
  • Play an audio clip
  • Resize the applet

In addition, the Applet class offers a line by which the spectator or browser gets knowledge concerning the applet and manages the applet's carrying out. The viewer might:

  • Request information about the author, version, and copyright of the applet
  • Request a description of the parameters the applet recognizes
  • Initialize the applet
  • Destroy the applet
  • Start the applet's execution
  • Stop the applet's execution

The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.

The "Hello, World" applet is total as it situates. The only technique overridden is the cover way.

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the "Hello, World" applet −

<html>
   <title>The Hello, World Applet</title>
   <hr>
   <applet code = "HelloWorldApplet.class" width = "320" height = "120">
      If your browser was Java-enabled, a "Hello, World"
      message would appear here.
   </applet>
   <hr>
</html>

Note − You preserve submit to HTML Applet Tag to appreciate more regarding calling applet from HTML.

The code quality of the <applet> tag is needed. It specifies the Applet group to run. Breadth and height are also necessitated to identify the first size of the board in which an applet sprints. The applet instruction must be locked with an </applet> tag.

If an applet gets parameters, worth maybe bypassed for the limits by adding <param> tags flanked by <applet> and </applet>. The browser disregards text and other tags amid the applet tags.

Non-Java-enabled browsers do not method <applet> and </applet>. As a result, something that emerges among the tags, not concerning to the applet, is noticeable in non-Java-enabled browsers.

The watcher or browser seems for the compiled Java system at the place of the document. To identify otherwise, use the codebase characteristic of the <applet> tag as exposed −

<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
   width = "320" height = "120">

If an applet exists in a wrap-up other than the defaulting, the asset wrap-up must be specified in the policy attribute by the period quality (.) to disconnect package/class components. For illustration:

<applet  = "mypackage.subpackage.TestApplet.class" 
   width = "320" height = "120">

Getting Applet Parameters

The subsequent example shows how to create an applet react to setup limits specified in the text. This applet exhibits a checkerboard outline of black and a subsequent color.

The following color and the amount of each square might be specified as limitations to the applet inside the document.

CheckerApplet gets its strictures in the init() technique. It may also obtain its parameters in the cover() method. Though, getting the worth and saving the locations once at the creation of the applet, rather than at each revive, is suitable and efficient.

The applet spectator or browser identifies the init() system of each applet it runs. The spectator calls init() once, straight away after loading the applet. (Applet.init() is applied to do nothing.) Supersede the default realization to insert custom initialization code.

The Applet.getParameter() method obtains a parameter known as the parameter's name (the worth of a parameter is always a string). If the worth is numeric or other non-character data, the cord must be parsed.

The following is a skeleton of CheckerApplet.java:

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

public class CheckerApplet extends Applet {
   int squareSize = 50;   // initialized to default size
   public void init() {}
   private void parseSquareSize (String param) {}
   private Color parseColor (String param) {}
   public void paint (Graphics g) {}
}

Here are CheckerApplet's init() and private parseSquareSize() methods:

public void init () {
   String squareSizeParam = getParameter ("squareSize");
   parseSquareSize (squareSizeParam);
   
   String colorParam = getParameter ("color");
   Color fg = parseColor (colorParam);
   
   setBackground (Color.black);
   setForeground (fg);
}

private void parseSquareSize (String param) {
   if (param == null) return;
   try {
      squareSize = Integer.parseInt (param);
   } catch (Exception e) {
      // Let default value remain
   }
}

The applet names parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the records method Integer.parseInt(), which parses a cord and revisits an integer. Integer.parseInt() throws an exemption whenever its row is invalid.

Consequently, parseSquareSize() catches exemptions, rather than authorizing the applet to be unsuccessful on bad input.

The applet calls parseColor() to parse the color stricture into a Color price. parseColor() does a sequence of string contrasts to match the limit worth to the name of a described color. You require to applying these methods to create this applet work.

Specifying Applet Parameters

The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML file specifies both parameters to the applet by means of the <param> tag.

<html>
   <title>Checkerboard Applet</title>
   <hr>
   <applet code = "CheckerApplet.class" width = "480" height = "320">
      <param name = "color" value = "blue">
      <param name = "squaresize" value = "30">
   </applet>
   <hr>
</html>

Application Conversion to Applets

It is trouble-free to exchange a graphical Java application (that is, a request that utilizes the AWT and that you can found with the Java list launcher) into an applet that you can implant in a web page.

  • Subsequent are the exact steps for exchanging an application to an applet.
  • Construct an HTML page with the apposite tag to consignment the applet code.
  • Provide a subclass of the JApplet class. Create this class community. if not, the applet never be loaded.
  • Eradicate the foremost system in the application. Do not raise a frame window for the request. Your application will be exhibited within the browser.
  • Shift any initialization system from the border window constructor to the init technique of the applet. You do not require to openly making the applet item. The browser instantiates it for you and identifies the init process.
  • Get rid of the call to setSize; for applets, sizing is complete with the breadth and stature parameters in the HTML file.
  • Eliminate the call to setDefaultCloseOperation. An applet never be closed; it concludes when the browser way outs.
  • If the application names setTitle, eradicate the call to the technique. Applets never encompass title bars. (You can title the web page itself, with the HTML title tag.)
  • Don't call setVisible(true). The applet is displayed automatically.

Event management

Applets come into a cluster of event-handling techniques from the pot class. The Container class describes numerous methods, such as processKeyEvent and processMouseEvent, for managing particular kinds of occasions, and then one catchall technique called processEvent.

In order to respond to an occasion, an applet must supersede the suitable event-specific technique.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class ExampleEventHandling extends Applet implements MouseListener {
   StringBuffer strBuffer;

   public void init() {
      addMouseListener(this);
      strBuffer = new StringBuffer();
      addItem("initializing the apple ");
   }

   public void start() {
      addItem("starting the applet ");
   }

   public void stop() {
      addItem("stopping the applet ");
   }

   public void destroy() {
      addItem("unloading the applet");
   }

   void addItem(String word) {
      System.out.println(word);
      strBuffer.append(word);
      repaint();
   }

   public void paint(Graphics g) {
      // Draw a Rectangle around the applet's display area.
      g.drawRect(0, 0, 
      getWidth() - 1,
      getHeight() - 1);

      // display the string inside the rectangle.
      g.drawString(strBuffer.toString(), 10, 20);
   }

   
   public void mouseEntered(MouseEvent event) {
   }
   public void mouseExited(MouseEvent event) {
   }
   public void mousePressed(MouseEvent event) {
   }
   public void mouseReleased(MouseEvent event) {
   }
   public void mouseClicked(MouseEvent event) {
      addItem("mouse clicked! ");
   }
}

Now, let us call this applet as follows:

<html>
   <title>Event Handling</title>
   <hr>
   <applet code = "ExampleEventHandling.class" 
      width = "300" height = "300">
   </applet>
   <hr>
</html>

Initially, the applet will display "initializing the applet. Starting the applet." Then once you click inside the rectangle, "mouse clicked" will be displayed as well.

Displaying Images

An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawImage() method found in the java.awt.Graphics class.

Following is an example illustrating all the steps to show images

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

public class ImageDemo extends Applet {
   private Image image;
   private AppletContext context;
   
   public void init() {
      context = this.getAppletContext();
      String imageURL = this.getParameter("image");
      if(imageURL == null) {
         imageURL = "java.jpg";
      }
      try {
         URL url = new URL(this.getDocumentBase(), imageURL);
         image = context.getImage(url);
      } catch (MalformedURLException e) {
         e.printStackTrace();
         // Display in browser status bar
         context.showStatus("Could not load image!");
      }
   }
   
   public void paint(Graphics g) {
      context.showStatus("Displaying image");
      g.drawImage(image, 0, 0, 200, 84, null);
      g.drawString("www.javalicense.com", 35, 100);
   }  
}

Now, let us call this applet as follows

<html>
   <title>The ImageDemo applet</title>
   <hr>
   <applet code = "ImageDemo.class" width = "300" height = "200">
      <param name = "image" value = "java.jpg">
   </applet>
   <hr>
</html>

Playing Audio

An applet can occupy yourself with an audio file symbolized by the AudioClip line in java.applet package. The AudioClip line has three processes, involving −

  • public void play() − Plays the audio clip one time, from the beginning.
  • public void loop() − Causes the audio clip to replay continually.
  • public void stop() − Stops playing the audio clip.

To get hold of an AudioClip object, you have to appeal to the getAudioClip() technique of the Applet class. The getAudioClip() system returns right away, whether or not the URL resolutions to a definite audio file. The audio file is not downloaded awaiting an effort is made to play the audio clip.

Following is an example illustrating all the steps to play audio:

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

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();
      }
   }
}

Now, let us call this applet as follows

<html>
   <title>The ImageDemo applet</title>
   <hr>
   <applet code = "ImageDemo.class" width = "0" height = "0">
      <param name = "audio" value = "test.wav">
   </applet>
   <hr>
</html>

You can use test.wav on your PC to test the above example.

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.