Java Applet Basics


Applet is a Java program. It typically runs within a Java-enabled web browser. Because it has full Java API support, the applet is a full-featured Java application.

The following are important differences between standalone Java applications and applet programs:

  •             The applet class in Java inherits the java.applet.Applet class

  •             The Applet class does not define main(), so an Applet program will not call the main() method,

  •             Applets are designed to be embedded in an HTML page.

  •           When a user browses an HTML page containing an Applet, the Applet's code is downloaded to the user's machine.

  •           To view an applet requires a JVM. The JVM can be a plug-in for a web browser, or a standalone runtime environment.

  •           The JVM on the user's machine creates an instance of the applet class and calls various methods during the Applet life cycle.

  •           Applets have strict security rules enforced by web browsers. The applet security mechanism is called sandbox security.

  •             Other classes required by the applet can be downloaded as Java archive (JAR) files.


Life cycle of Applet

The four methods in the Applet class provide you with a framework on which you can develop small programs:

  • init: The purpose of this method is to provide any initialization required for your applet. This method is called after the param tag within the Applet tag has been processed.

  • start: This method is automatically called after the browser calls the init method. This method is called whenever the user returns to the page containing the Applet from another page.

  • stop:This method is automatically called when the user removes from the page containing the applet. Therefore, the method can be called repeatedly in the same applet.

  • destroy: This method is only called when the browser is closed normally. Because applets are only valid on HTML pages, you should not miss any resources after the user leaves the page containing the applet.

  • paint: This method starts( ) method is called immediately afterwards, or when the applet needs to be redrawn in the browser. The paint() method actually inherits from java.awt.


"Hello, World" Applet:

The following is a simple Applet program 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 will The following classes are imported into our applet class:

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

Without these import statements, the Java compiler cannot recognize the Applet and Graphics classes.


Applet Class

Each applet is a subclass of the java.applet.Applet class. The basic Applet class provides methods for derived classes to call to obtain the browser context. Information and Services.

These methods do the following:

  • Get the parameters of the applet

  • Get the network location of the HTML file containing the applet

  • Get the network location of the applet class directory

  • Print the status information of the browser

  • Get A picture

  • Get an audio clip

  • Play an audio clip

  • Adjust this applet The size

In addition, the Applet class also provides an interface for the Viewer or browser to obtain applet information and control the execution of the applet.

Viewer may be:

  • Requesting information about the applet author, version and copyright

  • Requesting a description of the parameters recognized by the applet

  • Initialize applet

  • Destroy applet

  • Start executing applet

  • End execution of applet

The Applet class provides default implementations of these methods, which can be overridden when needed.

"Hello, World" applet is written according to standards. The only method that has been overridden is the paint method.


Calling Applet

Applet is a Java program. It typically runs within a Java-enabled web browser. Because it has full Java API support, the applet is a full-featured Java application.

<applet> tag is the basis for embedding applet in HTML files. The following is an example of calling 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 can refer to the HTML Applet tag to learn more about how to call an applet from HTML.

<applet>The attribute of the tag specifies the Applet class to be run. Width and height are used to specify the initial size of the applet running panel. Applets must be closed using the </applet> tag.

If the applet accepts parameters, the value of the parameter needs to be added in the label, which is located between <applet> and </applet>. The browser ignores text and other tags between applet tags.

Browsers that do not support Java cannot execute <applet> and </applet>. Therefore, anything displayed between tags that is not related to the applet will be visible in browsers that do not support Java.

Viewer or browser looks for compiled Java code at the location of the document. To specify the path of the document, you must use the codebase attribute of the <applet> tag.

As shown below:

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

If the applet is in a package other than the default package, the package must be specified in the code attribute, for example:

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

Get applet parameters

The following example demonstrates how to use an applet response to set parameters specified in a file. This Applet displays a black checkerboard pattern and a second color.

The second color and the size of each column are specified through the parameters of the applet in the document.

CheckerApplet gets its parameters in the init() method. You can also get its parameters in the paint() method. However, it is convenient and efficient to get the value at the beginning of the applet and save the settings, rather than getting the value every time it refreshes.

The applet viewer or browser calls the init() method every time the applet runs. Immediately after loading the applet, the Viewer calls the init() method (Applet.init() does nothing), overriding the default implementation of the method and adding some custom initialization code.

The Applet.getParameter() method gets the parameter value by giving the parameter name. If the resulting value is a number or other non-character data, it must be parsed as a string type.

The following example is the outline of CheckerApplet.java:

import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
   int squareSize = 50;// 初始化默认大小
   public void init () {}
   private void parseSquareSize (String param) {}
   private Color parseColor (String param) {}
   public void paint (Graphics g) {}
}

The following is the init() method and the private parseSquareSize() method of the CheckerApplet class:

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) {
     // 保留默认值
   }
}

The applet calls parseSquareSize (), to parse the squareSize parameter. parseSquareSize() calls the library method Integer. parseInt(), which parses a string into an integer. When the parameter is invalid, Integer.parseInt() throws an exception.

Therefore, the parseSquareSize() method also catches exceptions and does not allow the applet to accept invalid input.

Applet calls the parseColor() method to parse the color parameter into a Color value. The parseColor() method does a series of string comparisons to match the parameter value against the name of the predefined color. You need to implement these methods to make the applet work.


Specify applet parameters

The following example is an HTML file with the CheckerApplet class embedded in it. The HTML file specifies two parameters for the applet using tags.

<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>

Note: Parameter names are not case sensitive.


Convert applications to Applet

Convert graphical Java applications (referring to applications using AWT and programs launched using the java program launcher) into embedded The applet in the web page is very simple.

The following are a few steps to convert an application into an applet:

  • Write an HTML page with a tag that loads the applet code.

  • Write a subclass of the JApplet class and set the class to public. Otherwise, the applet cannot be loaded.

  • Eliminate the main() method of the application. Do not construct a frame window for your application because your application is displayed in the browser.

  • Move the initialization code in the construction method of the frame window in the application to the init() method of the applet. You do not have to explicitly construct the applet object. The browser will call init( ) method to instantiate an object.

  • Remove the call to the setSize() method. For applets, the size has been set through the width and height parameters in the HTML file.

  • Remove the call to the setDefaultCloseOperation() method. The applet cannot be closed; it terminates when the browser exits.

  • If the application calls the setTitle() method, eliminate the call to this method. Applets cannot have title bars. (Of course you can name the web page itself through the html title tag)

  • Do not call setVisible(true), the applet will be displayed automatically.


Event handling

The Applet class inherits many event handling methods from the Container class. The Container class defines several methods, such as processKeyEvent() and processMouseEvent(), to handle special types of events. There is also a method that captures all events called processEvent.

In order to respond to an event, the applet must override the appropriate event handling method.

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! ");
    }
}

Call the applet as follows:

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

When it is first run, the applet displays "initializing the applet. Starting the applet.", and then as soon as you click the rectangle, "mouse clicked" will be displayed. .


Display pictures

The applet can display pictures in GIF, JPEG, BMP and other formats. In order to display an image in an applet, you need to use the drawImage() method of the java.awt.Graphics class.

The following example demonstrates all the steps for displaying pictures:

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

Call the 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>

Play audio

The Applet can be used The AudioClip interface in the java.applet package plays audio. The AudioClip interface defines three methods:

  • public void play(): Play the audio clip once from the beginning.

  • public void loop(): Loop audio clips

  • public void stop(): Stop playing audio clips

#In order to get the AudioClip object, you must call the getAudioClip() method of the Applet class. Regardless of whether the URL points to a real audio file, this method will return the result immediately.

The audio file will not be downloaded until it is time to play it.

The following example demonstrates all the steps for playing 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();
      }
   }
}

Call the 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>

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