Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java Applet Foundation


May 10, 2021 Java


Table of contents


Java Applet Foundation

Applet is a Java program. I t typically runs in Java-supported Web browsers. Because it has full Java API support, applet is a full-featured Java application.

Here's an important difference between a stand-alone Java application and an applet:

  • The applet class in Java inherits the java.applet.Applet class
  • The Applet class does not define main(), so an Applet program does not call the main() method,
  • Applets is designed to be embedded in an HTML page.
  • When a user browses an HTML page that contains an applet, Applet's code is downloaded to the user's machine.
  • JVM is required to view an applet. JVM can be a plug-in for a Web browser or a stand-alone runtime environment.
  • The JVM on the user's machine creates an instance of the applet class and calls various methods during the applet lifecycle.
  • Applets has strict security rules enforced by web browsers, and Applet's security mechanisms are known as sandbox security.
  • Other classes required by applet can be downloaded in the form of Java Archive (JAR) files.

Applet's life cycle

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

  • init: The purpose of this method is to provide your applet with any initialization you need. The method is called after the param tag within the applet tag is processed.
  • Start: After the browser calls the init method, the method is called automatically. The method is called whenever a user returns from another page to a page that contains the applet.
  • stop: The method is automatically called when the user removes it from the page that contains the applet. Therefore, the method can be called repeatedly in the same applet.
  • destroy: This method is called only when the browser is normally closed. Because applets are only available on HTML pages, you should not leave out any resources after the user leaves the page containing the applet.
  • Paint: The method is called immediately after the start() method, or when the applet needs to be redrawn in the browser. The paint() method is actually inherited from java.awt.

"Hello, World" Applet:

Here's 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);
   }
}

Theseimport statements import the following classes into our applet class:

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

Without theseimport statements, the Java compiler would not have recognized the Applet and Graphics classes.


Applet class

Each applet is a sub-class of the java.applet.Applet class, and the underlying applet class provides methods for deriving class calls to get information and services in the browser context.

These methods do the following:

  • Get the parameters of the applet
  • Get the network location of the HTML file that contains the applet
  • Get the network location of the applet class directory
  • Print the browser's status information
  • Get a picture
  • Get an audio clip
  • Play an audio clip
  • Resize this applet

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

The Viewer might be:

  • Request information about the author, version, and copyright of the applet
  • Request a description of the parameters identified by the applet
  • Initialize the applet
  • Destroy the applet
  • Start executing the applet
  • End the execution of the applet

The Applet class provides a default implementation of these methods, which can be override when needed.

Hello, World applet is written by standard. The only way to be rewritten is the paint method.


Applet's call

Applet is a Java program. I t typically runs in Java-supported Web browsers. B ecause it has full Java API support, applet is a full-featured Java application.

The label is the basis for embedding the applet in the HTML file. H ere's an example of calling 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 learn more about how to call an applet from HTML by referring to the HTML Applet tag.

The properties of the label specify the applet class to run. W idth and height are used to specify the initial size of the applet run panel. Applet must be turned off using the hashtag.

If the applet accepts the argument, the value of the argument is required The label is added, and the label is located between the .lt;applet> and the .lt;/applet> The browser ignores text and other labels between the applet tags.

Browsers that do not support Java cannot perform . applet . . and . Therefore, anything that appears between labels and has nothing to do with the applet is visible in the browser of the unsupported Java.

The Viewer or browser looks for compiled Java code at the location of the document, and to specify the path to the document, you need to specify it using the codebase property of the label.

Here's what it looks like:

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

If the applet is in a package instead of the default package, the package must be specified in the code property, for example:

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

Get the applet parameters

The following example shows how to use an applet response to set the parameters specified in the file. The applet shows a black board pattern and a second color.

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

CheckerApplet gets its parameters in the init() method. Y ou can also get its parameters in the pass() method. H owever, it's convenient and efficient to get values at the beginning of the applet and save the settings, rather than getting values every time you refresh them.

The applet viewer or browser calls the init() method every time the applet is running. I mmediately after loading the applet, viewer calls the init(Applet.init() method (Applet.init() does nothing), rewrites the default implementation of the method, and adds some custom initialization code.

The Applet.getParameter() method obtains the parameter value by giving the parameter name. I f the resulting value is a number or other non-character data, it must be resolved to a string type.

The following example is a summary .java CheckerApplet:

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

Here's the init() method of the Checker Applet class and the private parseSquareSize() method:

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 parseSize parameters. P arseSquareSize() calls the library method Integer. p arseInt(), the method resolves a string to an integer, and When the argument 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 resolve the color parameters to a Color value. T he parseColor() method does a series of string comparisons to match the value of the argument and the name of the predefined color. Y ou need to implement these methods to make the applet work.


Specify the applet parameters

The following example is an HTML file embedded in the Checker Applet class. HTML files are used by using The label's method specifies two parameters for the applet.

<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: The case of the parameter name is insensitive.


The application is converted to an applet

Converting graphical Java applications (i.e., applications that use AWT and programs started with java program launchers) into applets embedded in web pages is simple.

Here are a few steps to converting an application into an applet:

  • Write an HTML page with a label that loads the applet code.
  • Write a sub-class of the JApplet class and set it to public. Otherwise, applet cannot be loaded.
  • Eliminate the application's main() method. Do not construct a frame window for your application because your application will appear in the browser.
  • To move the initialization code from the construction method of the frame window in your application to the init() method of the applet, you do not have to display the construction of the applet object, and the browser instantiates an object by calling the init() method.
  • To remove calls to the setSize() method, for the applet, the size has been set by the width and heat parameters in the HTML file.
  • Remove the call to the setDefaultCloseOperation() method. Applet cannot be shut down, it terminates with the browser exiting.
  • If the application calls the setTitle() method, the call to that method is eliminated. A pplet cannot have a title bar. (Of course you can name the page itself by using the htmltle tag)
  • Do not call setVisible (true), applet is displayed automatically.

Event processing

The Applet class inherits many event handling methods from the Container class. T he Container class defines several methods, such as processKeyEvent() and processMouseEvent(), which handle special types of events, and a method for capturing all events called processEvent.

In order to respond to an event, 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>

At the beginning of the run, applet displays "initializing the applet. S tarting the applet." And then as soon as you click on the rectangular box, you'll see "mouse clicked."


Displays the picture

Applet can display GIFs, JPEG, BMP and other formats of pictures. I n order to display pictures in the applet, you need to use the drawImage() method of the java.awt.Graphics class.

The following example demonstrates all the steps to display a picture:

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

Applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:

  • public void play(): Play the audio clip once from the beginning.
  • public void loop(): Loop the audio clip
  • public void stop(): Stop playing audio clips

In order to get the AutoClip object, you must call the getAudioClip() method of the Applet class. W hether or not the URL points to a real audio file, the method returns the results immediately.

The audio file will not be downloaded until you want to play it.

The following example demonstrates 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();
      }
   }
}

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 test the instance above .wav test the test on your computer.