Applet in Java

Applet in Java with Examples

In this article, I am going to discuss Applet in Java with Examples. Please read our previous article, where we discussed Multithreading in Java. As part of this article, we are going to discuss the following pointers in detail.

  1. What is Applet in Java?
  2. Types of Applets in Java
  3. Advantages & Drawbacks  of Java Applet
  4. The Applet Class in Java
  5. Methods of Applet Class
  6. Applet Life cycle in Java
  7. How to run Applets Programs in Java?
  8. What is Appletviewer?
  9. How to run the Applet Program using Appletviewer?
  10. Passing Parameters to Java Applet
Java Applet Introduction:

The Applet class is contained within java.applet package. The applet contains several methods that offer you detailed control over the execution of your applet. java.applet defines three interfaces : AppletContext, AudioClip, and AppletStub. This chapter examines the Applet class, which provides inspiration for applets.

Basically, in Java we have two types of applications:

  1. Standalone Applications: The applications that are executed in the context of a local machine are called standalone applications. Their applications use w-1 of system resources and the resources are not sharable. This kind of application contains the main() method.
  2. Distributed Applications: The applications that are executed under the control of a browser are called distributed applications. The amount of resources required is very minimum and the resources are sharable. These applications will not contain the main() method. To develop a distributed GUI we use Applet.
What is Applet in Java?

An applet may be a Java program that registers on the server and can be executed within the client. The applet may be a window that was constructed either by using Applet or JApplet class. Applets may be a special sort of program that’s embedded within the webpage to get the dynamic content. It basically runs inside the browser and works on the client-side.

All applets are subclasses of (either directly or indirectly) Applet. Applets aren’t standalone programs. Instead, they run within either an internet browser or an applet viewer. Execution of an applet doesn’t begin at the main(). Actually, few applets even have main() methods. Output to your applet’s window isn’t performed by System.out.println(). Rather, in non-Swing applets, the output is handled with various AWT methods, like drawString(), which outputs a string to a specified X, Y location.

Types of Applets in Java:

It is important to state at the outset that there are two sorts of applets.

  1. Applet: it’s based directly on Applet class. These applets use the Abstract Window Toolkit (AWT) to supply the graphic user interface(GUI). This sort of applet has been available since Java was first created.
  2. JApplet: it’s supported Swing class. Swing applets use the Swing classes to supply the GUI. Swing offers a richer and ofter easier-to-use interface than does the AWT. Thus, Swing-based applets are now the foremost popular.

Note: The Applet class is employed for enabling the AWT package to feature UI components and whereas JApplet class is employed for enabling the swing package to feature UI components.

Advantages of Java Applet

There are many advantages to the applet. they’re as follows:

  1. It works on the client-side therefore the reaction time is extremely less.
  2. It is Secured
  3. It is often executed by browsers running under many platforms, including Linux, Windows, Mac Os, etc.
Drawbacks of Applet in Java
  • The plugin is required at the client browser to execute the applet.
  • An applet cannot load libraries or define native methods.
  • An applet cannot read or write files on the execution host and certain system properties.
  • An applet cannot make network connections except to the host that it came from.
The Applet Class in Java

Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities.

Applet in Java with Examples

Methods of Java Applet Class

The Applet class defines the following methods:

  1. void destroy(): It is called by the browser just before an applet is terminated. If it needs to perform any clean up prior to its destruction, your applet will override this method.
  2. AccessibleContext getAccessibleContext(): It returns the accessibility context for the invoking object.
  3. AppletContext getAppletContext(): It returns the context associated with the applet.
  4. String getAppletInfo(): It returns a String that describes the applet.
  5. AudioClip getAudioclip(URL url): It returns an AudioClip found at the location specified by URL.
  6. AudioClip getAudioClip(URL url, String clipName): It returns an AudioClip object found at the location specified by URL and having the name specified by clipName.
  7. URL getCodeBase(): It returns the URL associated with the invoking applet.
  8. URL getDocumentBase(): It returns the URL of the HTML document.
  9. Image getImage(URL url): It returns an Image object that encapsulates the image of the location specified by the URL.
  10. 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.
  11. Locale getLocale(): It returns a Locale object used by various classes and methods.
  12. String getParameter(String paramName): It returns the parameter associated with paramName and returned Null if the parameter is not found.
  13. String[] [] getParameterInfo(): It returns a String table that contains the name of the parameter, a description of its type and/or range, and an explanation of its purpose.
  14. void init(): It is the first method called for any applet. It is called when an applet begins execution.
  15. boolean isActive(): It returns true if the applet has been started and returns false if the applet has been stopped.
  16. static final AudioClip new AudioClip(URL url): It returns an AudioClip found at the location specified by the URL. This method is similar to getAudioClip() except that it is static and can be executed without the need for an Applet object.
  17. void play(URL url): If an audio clip is found at the location specified by the URL, the clip is played.
  18. void play(URL url, String clipName): If an audio clip is found at the location specified by the URL with the name specified by clipName.
  19. void resize(Dimension dim): It is used to resize the applet according to the dimensions specified by dim.
  20. void resize(int width, int height): It is used to resize the applet according to the dimensions specified by width and height.
  21. final void setStub(AppletStub stubObj): Makes stubObj the stub for the applet. This method is used by the run-time system and is not usually called by your applet.
  22. void showStatus(String str): It is used to display str in the status window of the browser or applet viewer.
  23. void start(): It is called by the browser when an applet should start (or resume) execution. It is automatically called after the init() method.
  24. void stop(): It is called by the browser to suspend the execution of the applet. Once stopped, an applet is restarted when the browser calls start().
Applet Life cycle in Java:

Every Java Applet needs to go through a series of phases from initialization to destruction in order to complete its execution. The first step is to inherit the java.applet.Applet class. This class aids with various methods that help in holding up a basic framework for the Java Applets. The various methods involved in the life cycle of Java Applet have been depicted in the below diagram.

Applet Life cycle in Java

An applet is a window-based program. Its architecture is different from console-based programs. Applets are event-driven. An Applet waits until an event occurs. The run-time system notifies the applet about an event by calling an event handler provided by the applet. Then, the applet must take appropriate action and then quickly return. This is a crucial point.

The user can initiate the interaction with an Applet as he or she wants when he or she wants. These interactions are now sent to the applet as events to which the applet must respond. When the user interacts with any of the controls, an event is generated.

An Applet Skeleton

The applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. It is important to understand the order in which the various methods are called. When an applet begins, the following methods are called:

  1. init()
  2. start()
  3. paint()

When an applet is terminated, the following sequence of method calls takes place:

  1. stop()
  2. destroy()
Let’s look more closely at these methods.

init(): The init() method is the first method to be called where you ought to initialize variables. This method is named just one occasion during the run time of your applet.

start(): The start() method is named after init(). It’s also called to restart an applet after it’s been stopped. When start() is named whenever an applet’s HTML document is displayed onscreen. So, if a user leaves a webpage and comes back, the applet resumes execution at the start().

paint(): The paint() method is named whenever your applet’s output must be redrawn. This example can occur for several reasons. paint() is additionally called when the applet begins execution. The paint() method has a parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment during which the applet is running. This context is employed whenever output to the applet is required. 

stop(): The stop() method is named when an internet browser leaves the HTML document containing the applet- when it goes to a different page. When stop() is named, the applet is perhaps running. You ought to use stop() to suspend threads that don’t get to run when the applet isn’t visible. You’ll restart them when start() is named if the user returns to the page.

destroy(): The destroy() method is named when the environment determines that your applet must be removed completely from memory. At now, you ought to release any resources the applet could also be using. The stop() method is usually called before destroy().

Overriding update()

In some situations, your applet may need to override another method defined by the AWT, called update(). This method is called when your applet has requested that a portion of its window be redrawn. The default version of update() simply calls paint(). However, you can override the update() method so that it performs more subtle repainting. In general, overriding update() is a specialized technique that is not applicable to all applets.

How to run Applets in Java?

An Applet program is compiled in the same way as you have been compiling your console programs. However, there are two ways to run an applet.

  1. Using a Java-enabled web browser
  2. Using appletviewer
Using a Java-enabled web-browser

To use an Applet by a Java-enabled web browser, one way to do this is by using the APPLET tag. The applet is executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet, simply include a comment at the head of your Java source code file that contains the APPLET tag. Here is an example of such a comment:

/*
<applet code =”MyApplet” width=200 height=60>
</applet>
*/

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

Using appletviewer

An Applet viewer creates an environment that mocks the look and feel of a stand-alone program with no interaction with a web browser, even though it does involve a browser to run an applet. The Appletviewer is included with Sun’s JDK package, but not with Sun’s JRE package.

What is Appletviewer?

The AppletViewer is a standalone command-line program from Sun Microsystems to run Java applets. The Appletviewer is usually employed by developers for testing their applets before deploying them to an internet site. The Appletviewer command connects to the documents or resources designated by URLs and displays each applet referenced by the documents in its own window.

How does Appletviewer work?

As a Java developer, it’s a preferred option for running Java applets that don’t involve the utilization of an internet browser. The applet viewer logically takes the place of an internet browser, it functions very differently from an internet browser. The applet viewer operates on HTML documents, but all it’s for is embedded applet tags; the other HTML code within the document is ignored. Whenever the applet viewer encounters an applet tag in an HTML document, it launches a separate applet viewer window containing the respective applet.

How to run the Applet Program using Appletviewer?

This is the simplest way to run an applet. To execute a Java Applet in this way, all you would like to try to do is, rather than create a separate file for HTML code, you’ll directly add comments at the start of your Java ASCII text file indicating the presence of APPLET tag within. If you include a comment at the top of your Java ASCII text file that contains the APPLET tag then your code is documented with a prototype of the required HTML statements, and you’ll run your compiled applet merely by starting the applet viewer together with your Java ASCII text file.

Example: An Applet Skeleton in Java
import java.awt.*;
import java.applet.*;
/*
 <applet code ="AppletSkeleton" width=300 height=100>
 </applet>
 */
public class AppletSkeleton extends Applet
{
    public void init ()
    {
        //initialization
    }
    public void start ()
    {
        //start or resume execution
    }
    public void stop ()
    {
        //suspend execution
    }
    public void destroy ()
    {
        //perform shutdown activity
    }
    public void paint (Graphics g)
    {
        //display the content of window
    }
}
Output:

Although this skeleton does not do anything, it can be compiled and run. When run, it generates the following window when viewed with an applet viewer:

Applet Skeleton in Java

Creating Hello World Applet in Java
import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet 
public class HelloWorldApplet extends Applet
{
    // Overriding paint() method
    @Override public void paint (Graphics g)
    {
        g.drawString ("Hello World", 20, 20);
    }
}
Output:

Creating Hello World Applet in Java

Requesting Repaint : repaint() method

Whenever your applet needs to update the information displayed in its window, it simply calls repaint(). The repaint() method is defined by the AWT. It causes the AWT runtime system to execute a call to your applet’s update() method, which, in its default implementation, calls paint(). Thus, for another part of your applet to output to its window, simply store the output and then call repaint(). The AWT will then execute a call to paint(), which can display the stored information.

The repaint() method has four forms:

  1. void repaint()
  2. void repaint(int left, int top, int width, int height)

Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region are passed in width and height. These dimensions are specified in pixels.

  1. void repaint(long maxDelay)
  2. void repaint(long maxDelay, int x, int y, int width, int height)

Here, maxDelay specifies the maximum number of milliseconds that can elapse before the update (0 is called. If the time elapses before the update() can be called, it isn’t called. There’s no return value or exception thrown.

Example: Creating a Simple Banner using Applet in Java
import java.awt.*;
import java.applet.*;

/*
 <applet code ="RepaintApplet" width=300 height=50>
 </applet>
 */
public class RepaintApplet extends Applet implements Runnable
{
    String msg = "A simple Moving Banner.";
    Thread t = null;
    int state;
    boolean stopFlag;

    public void init ()
    {
        setBackground (Color.cyan);	// To set Background color of an Applet
        setForeground (Color.red);	// To set Foreground color of an Applet
    }

    public void start ()
    {
        t = new Thread (this);
        stopFlag = false;
        t.start ();
    }

    public void run ()
    {
        char ch;
        for (;;)
        { 
            try
            {
                repaint();
                Thread.sleep(250);
                ch = msg.charAt (0);
                msg = msg.substring(1, msg.length ());
                msg += ch;
                if (stopFlag)
                  break;
            }
            catch (InterruptedException ie)
            {
            }
        }
    }

    public void stop ()
    {
        stopFlag = true;
        t = null;
    }

    public void paint (Graphics g)
    {
        g.drawString (msg, 50, 30);
    }
}
Output:

Creating a Simple Banner using Applet in Java

Using the status window

In addition to displaying information in its window, an applet can also put a message to the status window of the browser or applet viewer on which it’s running. To do so, call showStatus() with the String that you simply want to be displayed. The status window may be a good place to offer the user feedback about its occurring within the applet, suggest options, or possibly report some sorts of errors.

Example to show the use of status window in Java
import java.awt.*;
import java.applet.*;

/*
 <applet code ="StatusWindow" width=300 height=50>
 </applet>
 */
public class StatusWindow extends Applet
{
    public void init ()
    {
        setBackground (Color.cyan);
    }
    public void paint (Graphics g)
    {
        g.drawString ("This is in the applet window", 10, 20);
        showStatus ("This is shown in the status window.");
    }
}
Output:

Example to show the use of status window in Java

Passing Parameters to Applet in Java

The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter() method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and Boolean values, you will need to convert their string representations into their internal formats.

Example: Passing Parameters to Applet in Java
import java.applet.Applet;
import java.awt.Graphics;
/*
 <applet code="ParamDemo" width="300" height="300">  
<param name=fontName value=Welcome>  
</applet>  
 */
public class ParamDemo extends Applet
{
    String fontName;
    public void init ()
    {
        fontName = getParameter ("pname");
        if (fontName == null)
            fontName = "Welcome to Applet Window";
        fontName = "Hello " + fontName;
    }
    public void paint (Graphics g)
    {
        g.drawString (fontName, 0, 10);
    }
}
Output:

Passing Parameters to Applet in Java

In the next article, I am going to discuss Graphics in Applet with examples. Here, in this article, I try to explain Applet in Java with Examples and I hope you enjoy this Applet in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *