YouTip LogoYouTip

Java Applet Basics

An Applet is a Java program. It generally runs within a Java-enabled web browser. Because it has full Java API support, an Applet is a fully functional Java application. Here are the key differences between a standalone Java application and an applet program: * In Java, the Applet class inherits from the `java.applet.Applet` class. * The Applet class does not define a `main()` method, so an applet program does not call the `main()` method. * Applets are designed to be embedded within 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, a JVM is required. The JVM can be a plugin for the 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's lifecycle. * Applets have strict security rules enforced by the web browser. The Applet's security mechanism is known as sandbox security. * Other classes required by the Applet can be downloaded in the form of a Java Archive (JAR) file. * * * ## Applet Lifecycle Four methods in the Applet class provide a framework on which you can build applets: * **init:** The purpose of this method is to provide any initialization your Applet needs. It is called after the `param` tags within the Applet tag have been processed. * **start:** This method is automatically called after the browser calls the `init` method. It is called each time the user returns to the page containing the Applet from another page. * **stop:** This method is automatically called when the user moves away from the page containing the Applet. Therefore, it can be called repeatedly within the same Applet. * **destroy:** This method is called only when the browser shuts down normally. Because Applets are only valid on HTML pages, you should not leave any resources behind after the user leaves the page containing the Applet. * **paint:** This 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: Below is a simple Applet program `HelloWorldApplet.java`: ## HelloWorldApplet.java File Code: ```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 following classes into our Applet class: `java.applet.Applet.` `java.awt.Graphics.` Without these import statements, the Java compiler would not recognize the Applet and Graphics classes. * * * ## Applet Class Every Applet is a subclass of the `java.applet.Applet` class. The base Applet class provides methods for derived classes to obtain information and services from the browser context. These methods do the following: * Get the Applet's parameters * Get the network location of the HTML file containing the Applet * Get the network location of the Applet class directory * Print the browser's status information * Obtain an image * Obtain an audio clip * Play an audio clip * Resize this Applet In addition, the Applet class provides an interface that a viewer or browser can use to obtain information about the Applet and to control the Applet's execution. The viewer might: * Request information about the Applet author, version, and copyright * Request a description of the parameters recognized by the Applet * Initialize the Applet * Destroy the Applet * Start executing the Applet * Stop executing the Applet The Applet class provides default implementations for these methods, which can be overridden as needed. The "Hello, World" applet is written in a standard way. The only method overridden is the `paint` method. * * * ## Invoking an Applet An Applet is a Java program. It generally runs within a Java-enabled web browser. Because it has full Java API support, an Applet is a fully functional Java application. The `` tag is the foundation for embedding an Applet in an HTML file. Here is an example invoking the "Hello World" applet: ## HTML Code: The Hello, World Applet
If your browser was Java-enabled, a "Hello, World" message would appear here.
**Note:** You can refer to the HTML Applet tag for more information on invoking applets from HTML. The attributes of the `` tag specify the Applet class to run. `width` and `height` specify the initial size of the Applet's display panel. The Applet must be closed with the `` tag. If the Applet accepts parameters, the parameter values need to be added within `` tags, which are placed between the `` and `` tags. The browser ignores any text and other tags between the applet tags. Browsers that do not support Java cannot execute `` and ``. Therefore, anything displayed between these tags that is not related to the applet will be visible in browsers that do not support Java. The viewer or browser looks for the compiled Java code at the location specified by the document. To specify the document's path, use the `codebase` attribute of the `` tag. As shown below: If the Applet is in a package other than the default package, the package must be specified in the `code` attribute, for example: ## Getting Applet Parameters The following example demonstrates how to use an Applet response to set parameters specified in a file. The Applet displays a black checkerboard pattern and a second color. The second color and the size of each square are specified by parameters for the Applet in the document. The `CheckerApplet` gets its parameters in the `init()` method. It could also get its parameters in the `paint()` method. However, it is convenient and efficient for the Applet to get and save the settings at startup rather than getting them each time the Applet is repainted. The Applet viewer or browser calls the `init()` method each time the Applet is run. After loading the Applet, the viewer immediately calls the `init()` method (which does nothing by default), overriding this default implementation with custom initialization code. The `Applet.getParameter()` method gets the value of a parameter by giving its name. If the value obtained is numeric or other non-character data, it must be parsed. The following is a modification of `CheckerApplet.java`: ## CheckerApplet.java File Code: ```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){} } Below are the `init()` method and the private `parseSquareSize()` method of the `CheckerApplet` class: ```java 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 the exception and does not allow the Applet to accept invalid input. The Applet calls the `parseColor()` method to parse the color parameter into a `Color` value. The `parseColor()` method performs a series of string comparisons to match the parameter value to predefined color names. You need to implement these methods to make the Applet work. * * * ## Specifying Applet Parameters The following example is an HTML file that embeds the `CheckerApplet` class. The HTML file specifies two parameters for the applet using `` tags. Checkerboard Applet

**Note:** Parameter names are case-insensitive. * * * ## Converting an Application to an Applet Converting a graphical Java application (i.e., an application using AWT and launched by the Java program launcher) into an applet embedded in a web page is straightforward. Here are the steps to convert an application to an Applet: * Write an HTML page with a tag that can load the applet code. * Write a subclass of `JApplet`, making the class public. Otherwise, the Applet cannot be loaded. * Eliminate the `main()` method of the application. Do not construct a frame window for the application, as your application will be displayed in the browser. * Move the initialization code from the frame window's constructor to the Applet's `init()` method. You do not need to explicitly construct the Applet object; the browser will instantiate it by calling the `init()` method. * Remove the call to `setSize()`. For an Applet, the size is already set by the `width` and `height` parameters in the HTML file. * Remove the call to `setDefaultCloseOperation()`. An Applet cannot be closed; it terminates when the browser exits. * If the application called `setTitle()`, eliminate that call. An applet cannot have a title bar. (Of course, you can name the web page itself using the HTML `` tag.) * Do not call `setVisible(true)`. The Applet is 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 specific types of events, and a method called `processEvent` to capture all events. To respond to an event, the Applet must override the appropriate event-handling method. ## ExampleEventHandling.java File Code: ```java 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 applet "); } 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){ g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); 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! "); } } Invoke the Applet as follows: <title>Event Handling

When first run, the Applet displays "initializing the applet. Starting the applet." Then, when you click the rectangle, it displays "mouse clicked". * * * ## Displaying Images Applets can display images in formats such as GIF, JPEG, BMP, etc. 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 to display an image: ## ImageDemo.java File Code: ```java 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(); 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); } } Invoke the applet as follows: The ImageDemo applet

* * * ## Playing Audio Applets can play audio using the `AudioClip` interface in the `java.applet` package. The `AudioClip` interface defines three methods: * **public void play():** Plays the audio clip once from the beginning. * **public void loop():** Plays the audio clip in a loop. * **public void stop():** Stops playing the audio clip. To obtain an `AudioClip` object, you must call the `getAudioClip()` method of the Applet class. This method returns immediately, regardless of whether the URL points to an actual audio file. The audio file is not downloaded until it is time to play it. The following example demonstrates all the steps to play audio: ## AudioDemo.java File Code: ```java 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(); } } } Invoke the applet as follows: The ImageDemo applet

You can use a `test.wav` file on your computer to test the above example.
← Java DocumentationJava Multithreading β†’