Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Java applet?
2.1.
Example
3.
Life Cycle of Java Applet
3.1.
Initialization
3.2.
Start
3.3.
Paint
3.4.
Stop
3.5.
Destroy
4.
Hierarchy of Java Applet
4.1.
Object
4.2.
Component
4.3.
Container
4.4.
Panel
4.5.
Applet
4.6.
JApplet
5.
How to run an applet?
5.1.
By html file
5.2.
By appletViewer tool
6.
Example of Java Applet File
6.1.
Event Handling
6.2.
java
6.3.
html
6.4.
File Directory Structure
6.5.
Drawing Shapes
6.6.
java
6.7.
html
7.
Advantages of applets
8.
Disadvantages of applets
9.
Frequently Asked Questions
9.1.
Q. What is Java Applet?
9.2.
Q. How to write Java applet?
9.3.
Q. What is the use of applet class in Java?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java Applet

Author Gaurav Gandhi
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

An applet is a Java program that is executed within a web browser. Applets are the way to go if you want to add interactivity and visual appeal to your websites. In this article, we will explore everything related to Java Applets.

Java Applet

What is a Java applet?

A Java Applet is a type of program that runs in a web browser. It was intended to be embedded in an HTML page and run on the client side. So, the applet code is downloaded from the server to the user's computer and executed by the browser.

The Applet class is a Java standard library predefined class that offers a foundation for designing and executing applets. It is defined in the java.applet package and provides the foundation for all applets.

To create a Java Applet, we need to create a subclass of the 'Applet' class and override its methods such as 'init()' and 'paint()'. We will study about them in more detail later.

Here is an example of a Java Applet class:

Example

// Import the necessary packages
import java.applet.Applet;
import java.awt.Graphics;

// Define a class that extends the Applet class
public class MyFirstApplet extends Applet {

   // Override the init() method to perform initialization
    public void init() {
      // Initialization code goes here
    }
	public void start() {
      // Start or resume execution
    }
	public void stop() {
      // Suspend execution
    }
	public void destroy() {
      // Perform complete shutdown
    }

   // Override the paint() method to perform rendering
   public void paint(Graphics g) {
      // Drawing code goes here
   }
}


We first import the applet-related packages java.applet.Applet and java.awt.Graphics.

We define MyFirstApplet class, which extends the Applet class. This means that our class will inherit all of the Applet class's methods and properties, and we will be able to override some of these methods to customize the behavior of our applet.

After defining your applet class, you can compile and embed it in an HTML page with the applet element, as shown in the next topic.

Although this skeleton code does nothing, it can be compiled and run. This is the output it generates when viewed with an applet viewer:

Output:

sample ouput of applet

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Life Cycle of Java Applet

A Java Applet's life cycle consists of a series of methods that are called at various stages of the applet's execution. These methods are:

Java Applet Life Cycle

Let's understand these methods one-by-one in detail:

Initialization

Unlike regular Java codes, there is no method in the Java applet. Every applet starts its execution from the init() method and is executed only once.

Syntax

public void init()

Start

After the init() method is invoked in the applet, the start() method is invoked when the browser is maximized.
So, if a user leaves the webpage and comes back again, the Applet program starts from the start().

Syntax

public void start()

Paint

We use the paint() method to display content on the applet. We can create objects, write text on the applet and take the Graphics class as a parameter.
The parameters contain the graphic context, which describes the graphical environment during which the Java Applet is running.

Syntax

public void paint(Graphic g)

Stop

stop() is used to stop the applet. It gets invoked when the browser is minimized.
It also suspends threads that don't get to run whenever the applet isn't visible.

Syntax

public void stop()

Destroy

destroy() method is called when we need to completely close the applet. It gets executed when the applet is closed.
It also releases any resources the applet program was holding.

Syntax

public void destroy()

Hierarchy of Java Applet

Applet class extends Panel, as shown in the diagram below. The Container and Component are extension of Panel.

Hierarchy of java applet

In Java, the applet hierarchy can be thought of as a tree-like structure with various classes and interfaces forming the branches of the tree. Here's how the classes and interfaces mentioned in diagram fit into this hierarchy:

Object

This is the base of the Java class hierarchy and the base class for all Java classes, including those used by applets.

Component

This is a subclass of Container and is the base class for all visual elements that can be displayed on screen for example, buttons, text boxes, images. Components have a size and position on the screen and can respond to user input.

Container

This is a subclass of Panel and is used to hold other visual elements such as buttons and text boxes. A container can be thought of as a box that can contain other boxes, such as Russian nesting dolls.

Panel

This is a subclass of Applet, a base container that can contain other components. Panels are often used to group related components, such as a group of buttons that perform all related actions.

Applet

This is a subclass of Applet package, designed specifically for use as an applet in a web browser. Applets have a lifecycle managed by the browser and can communicate with the web page containing the applet.

JApplet

JApplet is provided by the Swing UI Toolkit. Swing is a more modern and flexible toolkit than the old AWT (Abstract Window Toolkit) used to create applets in the past. JApplet can be customized with various Swing components and is often used to create more sophisticated applets with advanced user interfaces.

How to run an applet?

An applet can be run two ways:

By html file

To run an applet through an HTML file, follow these steps:

1. Create the Applet Class: Write your applet code by creating a class that extends ‘java.applet.Applet’.

2. Write the HTML File: Create an HTML file and use the `<applet>` tag to embed the applet in the HTML page. Here's a basic example:

<!DOCTYPE html>
  <html>
  <head>
     <title>Applet Example</title>
  </head>
  <body>
     <applet code="YourAppletClass.class" width="300" height="200"></applet>
  </body>
  </html>

Replace `"YourAppletClass.class"` with the name of your applet's compiled class file.

3. Run in Browser: Open the HTML file in a web browser that supports Java applets. Keep in mind that modern browsers may have limited or no support for Java applets due to security and technology changes.

By appletViewer tool

The `appletviewer` tool allows you to run Java applets without needing a web browser. Here's how:

1. Compile the Applet Class: Compile your applet class using the Java compiler. For example, if your applet class is ‘YourAppletClass.java’:

javac YourAppletClass.java

2. Run `appletviewer`:Open a terminal or command prompt and use the `appletviewer` tool to run the applet. Use the following command:

appletviewer YourAppletClass.html

Replace `YourAppletClass.html` with the HTML file that embeds your applet. The `appletviewer` tool will launch and display the applet's output in a separate window.

Example of Java Applet File

Below are two examples of java applet file event handling and drawing shapes. These programs will give you a better understanding of Java applets.

Event Handling

In the below example, we will define an applet called ‘eventhandling’ that will include a button and a label. In the ‘init()’ method, we will create the button and add action listeners to it using the ‘addActionListener()’ method. We also create a label and add it to the applet.

The ‘actionPerformed()’ method is called whenever the button is clicked. In this method, we check if the source of the event is the button, and if so, we update the label text using the ‘setText()’ method.

Save this file as eventhandling.java

  • java

java

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class eventhandling extends Applet implements ActionListener {
  private Button myButton;
  private Label myLabel;

  public void init() {
     myButton = new Button("Click me!");
     myButton.addActionListener(this);
     add(myButton);
   
     myLabel = new Label("Button");
     add(myLabel);
  }

  public void actionPerformed(ActionEvent evt) {
     if (evt.getSource() == myButton) {
        myLabel.setText("Button clicked!");
     }
  }
}


To run this applet, you can embed it in an HTML file and open it in a web browser, like so:

  • html

html

<applet code="eventhandling.class" width="200" height="200"></applet>


Make sure that the ‘evenhandling.class’ file is in the same directory as the HTML file.

Output

Ouput before button is clicked

 

When you click on the on the “Click me!” button you get the following output.

Output after button is clicked

File Directory Structure

The HTML file and Java code and class file should be in the same directory as show below:

file directory structure

Drawing Shapes

In the below example we will define a class ‘shapes’ that overrides the ‘paint()’ method to draw various shapes using the ‘Graphics’ object. We draw a rectangle, oval and polygon.

Save this code as shapes.java

  • java

java

import java.applet.*;
import java.awt.*;

public class shapes extends Applet {
  public void paint(Graphics g) {
     // Draw a rectangle
     g.drawRect(10, 10, 50, 50);

     // Draw a filled rectangle
     g.fillRect(70, 10, 50, 50);

     // Draw an oval
     g.drawOval(130, 10, 50, 50);

     // Draw a filled oval
     g.fillOval(190, 10, 50, 50);

     // Draw a line
     g.drawLine(250, 10, 300, 60);

     // Draw a polygon
     int[] xPoints = { 10, 30, 50 };
     int[] yPoints = { 100, 70, 100 };
     g.drawPolygon(xPoints, yPoints, 3);

     // Draw a filled polygon
     int[] xPoints2 = { 70, 90, 110 };
     int[] yPoints2 = { 100, 70, 100 };
     g.fillPolygon(xPoints2, yPoints2, 3);
  }
}


The drawRect method is commonly used in graphics programming to draw a rectangle onto a canvas or graphical user interface. Takes four arguments that define the position and dimensions of the rectangle.

The first argument (10 in this case) gives the x-coordinate of the top left corner of the rectangle.
The second argument (10 in this case) gives the y coordinate of the upper left corner of the rectangle.
The third argument (50 in this case) specifies the width of the rectangle.
The fourth argument (50 in this case) specifies the height of the rectangle. So the given code draws a rectangle with the upper left corner at coordinates (10, 10) and a width and height of 50 pixels each. 

Similarly we can add parameters for drawOval, drawLine, drawPolygon.

To run this applet, you can embed it in an HTML file and open it in a web browser, like so:

  • html

html

<applet code="shapes.class" width="300" height="200"></applet>


Make sure that the ‘shapes.class’ file is in the same directory as the HTML file.

Output

Output for various shaped drawn

Also see, Hashcode Method in Java

Advantages of applets

Here are some advantages of java applets: 

  • Rich User Interface: Applets enable the creation of appealing and interactive user interfaces, on web browsers, including animations, graphics and elements, for user input.
     
  • Platform Independence: Applets can run on the Java Virtual Machine (JVM) which means they are not tied to an operating system. This allows a single applet to be executed across operating systems without any modifications needed.
     
  • Code Reusability: With Java applets developers can easily reuse existing Java libraries saving time and effort in the development process.
     
  • Easy Distribution: Applets can be seamlessly embedded within HTML pages making it convenient to distribute and share them over the internet.
     
  • Security Model: Javas applet security model ensures that applets operate within a sandbox environment. This significantly reduces the risk of any code causing harm to the host system.
     
  • Updates: Since applets are loaded from servers, any updates or changes made to an applet can be applied on the server side. As a result users will automatically receive the version without needing intervention.

Disadvantages of applets

Here are some disadvantages of java applets: 

  • Browser Support: web browsers for Java applets is limited or nonexistent due to security concerns and the emergence of technologies such as HTML5 and JavaScript.
     
  • Performance: One drawback of using applets is that they may experience performance issues since they require loading the JVM and can be slower to start compared to web technologies.
     
  • Security Concerns: Although applets run in an environment there have been instances of security vulnerabilities, which raises concerns, about their safety.
     
  • Plugin Dependency: To run applets a Java browser plugin is often needed,. This can lead to compatibility problems and security risks.
     
  • Limited Mobile Support: Java applets are not well suited for devices as many mobile platforms do not support their execution.
     
  • Decreasing Popularity: Due to the disadvantages mentioned above and the advent of more versatile web technologies, Java applets have seen a decline in popularity and usage.

Frequently Asked Questions

Q. What is Java Applet?

A Java Applet is a program or application that is written in the Java programming language and can be embedded within a web browser. Its purpose is to enhance webpages, with content, such as animations, graphics and user interface elements.

Q. How to write Java applet?

To create a Java applet, you will need to develop a class that extends the `java.applet.Applet` class. This will involve overriding the `init()` method to set up the state of the applet and, optionally, the `paint()` method to determine how its graphical output should be displayed.

Q. What is the use of applet class in Java?

In Java, the `applet` class is represented by the `java.applet.Applet`. It actually serves as the foundation for building applets. It offers various methods, like `init()` `start()` `stop()` and `destroy()` which manages the lifecycle of applets.

Conclusion

In conclusion, Java applets are powerful tools that allow developers to create interactive and dynamic applications that run in the web browser. They were widely used in the early 2000s, providing a way to create a rich web content before the advent of modern web technologies like HTML5 and JavaScript.

To learn more about Java.

To learn more about Java Applet and Java Applet Life Cycle.

If you liked our article, do upvote our article and help other ninjas grow. You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Happy Learning!

Previous article
Introduction to Packages
Next article
Java Packages List
Live masterclass