Latest web development tutorials

Java Applet foundation

Java Applet foundation

An applet is a Java program. It generally runs in a Java-enabled Web browser. Because it has full support for Java API, so the applet is a full-featured Java applications.

Below is an important difference between the stand-alone Java application and applet programs:

  • Java applet class inherits the class java.applet.Applet
  • Applet class does not define main (), so the program does not call an Applet main () method,
  • Applets are designed to be embedded in an HTML page.
  • When a user browses an HTML page that contains the Applet, Applet code is downloaded to the user's machine.
  • To view an applet needs JVM. JVM can be a plug-in Web browser, or a separate runtime environment.
  • JVM user machine to create an instance of the applet class, and calls the Applet life cycle of the various methods.
  • Applets have strict security rules Web browser enforceable security applet is called sandbox security.
  • Form applet need other classes can use the Java Archive (JAR) file is downloaded.

Applet lifecycle

Applet class provides four methods give you a framework, you can be on the framework for the development of small program:

  • init: The purpose of this method is to provide any initialization needed for your applet. This method is called after the param tag Applet tags is processed.
  • start: the browser calls the init method, which is called automatically. Whenever the user returns to the page from other pages containing the Applet, then call the method.
  • stop: When a user is removed from the page containing the applet, the method is called automatically. Therefore, this method can be called repeatedly in the same applet.
  • destroy: This method is called only when the browser is shut down gracefully. Because applets after only valid on the HTML page, so you should not be in the user leaves the page that contains the Applet miss any resources.
  • paint: This method is called immediately after the start () method, or applet needs to be redrawn when the browser calls. paint () method actually inherited from java.awt.

"Hello, World" Applet:

Here 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 statements import the following classes into our applet class:

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

Without these import statements, Java compiler will not recognize Applet and Graphics classes.


Applet class

Each applet subclass of Applet classes are java.applet.Applet base class provides a method for the derived class calls, in order to obtain information and services browser context.

These methods do the following things:

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

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

Viewer may be:

  • Request applet author, version and copyright information
  • Request description parameter identification applet
  • Initialization applet
  • Destruction applet
  • Begin applet
  • End execution applet

Applet class provides a default implementation of these methods, these methods can be overridden when needed.

"Hello, World" applet are prepared according to standard. The only way to be overridden paint method.


Applet call

An applet is a Java program. It generally runs in a Java-enabled Web browser. Because it has full support for Java API, so the applet is a full-featured Java applications.

<Applet> tag is based applet embedded in an HTML file. The following is a call to "Hello World" applet example;

<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 HTML Applet tag to learn more about the applet method call from the HTML.

Properties <applet> tag specifies the Applet class to run. Width and height used to specify the initial size of the applet to run the panel. applet must use the </ applet> tag to close.

If the applet accepts parameters, then the value of the parameter required Add tags, the tag is located in <applet> and </ applet> between. Browsers ignore the text and other labels applet tags.

Does not support Java browser can not execute <applet> and </ applet>. Therefore, between the label and the applet display and nothing relationship, without the support of Java browser it is visible.

Viewer or browser to find the location in the document compiled Java code, to specify the document path, have to use <applet> codebase attribute specifies the tag.

As follows:

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

If the applet where a package instead of the default package, the package must be specified in the code where the property where, 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 the parameters specified in the file. The Applet shows a black checkerboard pattern and a second color.

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

CheckerApplet get its parameters in init () method inside. You can also get its parameters in paint () method inside. However, in the applet start getting value and save the settings, rather than when they are refreshed every time get the value, so it is convenient and efficient.

applet viewer or browser when the applet runs each call init () method. After loading the applet, Viewer immediately call init () method (Applet.init () did nothing), override the default implementation of this method, add some custom initialization code.

Applet.getParameter () method is given by the parameter name parameter value obtained. If the value obtained is a number or other non-character data, you must resolve to a string type.

The following example is CheckerApplet.java Synopsis:

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 is CheckerApplet class init () method and 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 call parseSquareSize (), to resolve squareSize parameters. parseSquareSize () method calls the library Integer. parseInt (), which will parse a string to an integer, when the parameter is not valid when, Integer.parseInt () throws an exception.

Therefore, parseSquareSize () method also catch the exception, and the applet is not allowed to accept invalid input.

Applet call parseColor () method of the color parameter resolves to a Color value. parseColor () method were compared a series of strings to match the value of the parameter and a predefined color name. You need to implement these methods to make the applet work.


Specify applet parameters

The following example is an HTML file that embeds CheckerApplet class. HTML file by using Applet tag method to specify the two parameters.

<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 parameter names are not case sensitive.


Applications into Applet

The graphical Java applications (refers to the use of AWT application and use java program launcher programs) into embedded in the web page where the applet is very simple.

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

  • Write an HTML page that can be loaded with the applet tag code.
  • Write a JApplet subclass, the class is set to public. Otherwise, applet can not be loaded.
  • Eliminate the application of main () method. Do not construct the framework for the application window because your application to be displayed in the browser.
  • The constructor application frame window where the initialization code to the applet's init () method, the configuration applet object you do not display the browser by calling the init () method to instantiate an object.
  • Remove the call to setSize () method, the applet is concerned, the size has been set up by the HTML file in the width and height parameters.
  • Remove the call to setDefaultCloseOperation () method. Applet can not be closed, as it exits the browser is terminated.
  • If the application calls setTitle () method, the elimination of calling this method. applet can not have a title bar. (Of course, you can give through the html title tag for the page itself is named)
  • Do not call setVisible (true), applet is automatically displayed.

Event Processing

Applet class inherits a number of event handler method from the Container class. Container class defines several methods, such as: processKeyEvent () and processMouseEvent (), to handle particular types of events, there is a method to capture all events called processEvent.

In response to an event, applet must override the appropriate event handler 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 following applet:

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

Most started running, applet display "initializing the applet. Starting the applet.", And then you click on a rectangle, it will show "mouse clicked".


display image

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

The following examples demonstrate all the steps to display 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);
   } 
}

Call the following applet:

<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 through the use java.applet package AudioClip play audio interfaces. AudioClip interface defines three methods:

  • public void play (): From the beginning once play this audio clip.
  • public void loop (): loop play this audio clip
  • public void stop (): Stop an audio clip

In order to obtain AudioClip object, you must call getAudioClip () method Applet class. No matter whether the URL points to a real audio file, which will return the results immediately.

Until you want to play an audio file, the file will be downloaded.

The following examples demonstrate the steps to play all 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();
      }
   }
}

The following call applet:

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