Programs

What is Applet in Java? How to Create & Run?

Java applets are short programs created in Java or another programming language that combines Java bytecode and is provided to users as Java bytecode. Java applet was launched by the user from a web page, and it was then processed within a Java virtual machine (JVM) in a procedure distinct from the web browser. A Java applet might appear in a web page frame, a new application window, Sun’s AppletViewer, or a standalone applet testing tool.

Applets give interactive capabilities to web applications that HTML cannot deliver. They can record mouse input and feature controls such as buttons or checkboxes. In addition, an applet can modify the offered graphic information in response to user activities. As a result, applets are ideal for presentation, visualisation, and education.

An applet is a web application embedded in an HTML page with the APPLET or OBJECT tag and hosted on a web server. Applets are utilised to enhance the website’s dynamic and engaging nature.

 Example of an Applet

 import java.applet.*;

import java.awt.*;

public class MyApplet extends Applet

{

 int height, width;

 public void init()

 {

  height = getSize().height;

  width = getSize().width;

  setName(“MyApplet”);

 }

 public void paint(Graphics g)

 {

  g.drawRoundRect(10, 30, 120, 120, 2, 3);

 }

}

 Here’s an example of a Java source code for making a simple calculator using an Applet. The result of the application is also presented below:

/*Java Program to Demonstrate a Basic Calculator using Applet*/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class Calculator extends Applet implements ActionListener

{

TextField inp;

//Function to add features to the frame

public void init()

{

         setBackground(Color.white);

         setLayout(null);

         int i;

         inp = new TextField();

         inp.setBounds(150,100,270,50);

         this.add(inp);

         Button button[] = new Button[10];

         for(i=0;i<10;i++)

         {

         button[i] = new Button(String.valueOf(9-i));

         button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);

         this.add(button[i]);

         button[i].addActionListener(this);

         }

         Button dec=new Button(“.”);

         dec.setBounds(200,300,50,50);

         this.add(dec);

         dec.addActionListener(this);

     Button clr=new Button(“C”);

         clr.setBounds(250,300,50,50);

         this.add(clr);

         clr.addActionListener(this)

         Button operator[] = new Button[5];

         operator[0]=new Button(“/”);

         operator[1]=new Button(“*”);

         operator[2]=new Button(“-“);

         operator[3]=new Button(“+”);

         operator[4]=new Button(“=”);

         for(i=0;i<4;i++)

         {

         operator[i].setBounds(300,150+(i*50),50,50);

         this.add(operator[i]);

         operator[i].addActionListener(this);

         }

         operator[4].setBounds(350,300,70,50);

         this.add(operator[4]);

         operator[4].addActionListener(this);

}

String num1=””;

String op=””;

String num2=””;

//Function to calculate the expression

public void actionPerformed(ActionEvent e)

{

         String button = e.getActionCommand();

     char ch = button.charAt(0);

         if(ch>=’0′ && ch<=’9’|| ch==’.’)

         {

         if (!op.equals(“”))

                     num2 = num2 + button;

         else

                     num1 = num1 + button;  

         inp.setText(num1+op+num2);

         }

         else if(ch==’C’)

         {

         num1 = op = num2 = “”;

         inp.setText(“”);

         }

         else if (ch ==’=’)

         {

         if(!num1.equals(“”) && !num2.equals(“”))

         {

                     double temp;

                 double n1=Double.parseDouble(num1);

                     double n2=Double.parseDouble(num2);

                     if(n2==0 && op.equals(“/”))

                     {

                     inp.setText(num1+op+num2+” = Zero Division Error”);

                     num1 = op = num2 = “”;

                     }

                     else

                     {

                     if (op.equals(“+”))

                         temp = n1 + n2;

                     else if (op.equals(“-“))

                         temp = n1 – n2;

                     else if (op.equals(“/”))

                         temp = n1/n2;

                     else

                         temp = n1*n2;

                     inp.setText(num1+op+num2+” = “+temp);

                     num1 = Double.toString(temp);

                     op = num2 = “”;

             }

         }

         else

         {

                     num1 = op = num2 = “”;

                     inp.setText(“”);

         }

     }

         else

         {

         if (op.equals(“”) || num2.equals(“”))

                     op = button;

         else

         {

                     double temp;

                     double n1=Double.parseDouble(num1);

                     double n2=Double.parseDouble(num2);

                     if(n2==0 && op.equals(“/”))

                     {

                     inp.setText(num1+op+num2+” = Zero Division Error”);

                     num1 = op = num2 = “”;

                     }

                     else

                     {

                     if (op.equals(“+”))

                         temp = n1 + n2;

                     else if (op.equals(“-“))

                         temp = n1 – n2;

                     else if (op.equals(“/”))

                         temp = n1/n2;

                     else

                         temp = n1*n2;

                     num1 = Double.toString(temp);

                     op = button;

                     num2 = “”;

             }

         }

         inp.setText(num1+op+num2);

     }

}

}

/*

<applet code = Calculator.class width=600 height=600>

</applet>

*/

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

 Advantages of an Applet:

  1. Since an applet is a short Java application, it is a platform-neutral code that can run on any browser.
  1. On client-side computers, applets may execute various minor activities. They can play music, display images, receive user inputs, mouse clicks, and even keystrokes, among other things.
  1. Applets are client-side visuals that are distinct and independent of the client-side platform.
  1. Although applets are less in size than stand-alone applications, their ability to be shared across a network makes them more usable.
  1. Since applets run on client browsers, they may import graphics and audio snippets depending on URLs.
  1. Due to their access to resources, applets are highly secure.
  1. Applets are safe and protected to use since they cannot modify the local system.
  1. Applets operating via Intranets may perform multiple tiny activities such as login, inventory checking, and task scheduling.

 Limitations of an Applet:

 Since applets are received from distant workstations and might affect client-side machines, they are subject to several security constraints. Here are a few examples:

  1. If someone is running an applet from an unreliable supplier, security is critical.
  1. Any programme on the local system cannot be started or modified by the applet.
  1. Applets do not have access to client-side resources such as files, operating systems, and so on.
  1. Applets may be granted specific rights. They must be labelled as trustworthy applets and registered with APS (Applet Security Manager).
  2. When it comes to interacting, Applet has few constraints. It can only communicate with the machine that loaded it.
  3. Applets are unable to interact with native methods.
  1. The only information an applet may collect about a client machine is its name, java edition, operating system, version, and so on.
  1. Applets are notoriously sluggish to execute because all of the classes and resources they require must be sent across the network.

Popular Courses & Articles on Software Engineering

 Life Cycle of an Applet:

 There are five techniques in the applet life cycle. Init(), start(), paint(), stop(), and destroy() are the methods.

init(): The init() function is used to launch an applet. It is only called once throughout the startup process. The internet browser generates objects that have already been initialised. This technique is equivalent to the Thread class’s condition of being born.

start(): The start() function is used to initiate the execution of the applet. It is invoked after the init() function has been called. Whenever the browser loads or refreshes, it is called. The start() function is dormant until the init() method is called. This function is comparable to the Thread class’s start state.

 paint(): The paint() function is used to paint any form such as a square, rectangle, trapezium, eclipse, etc. ClassGraphics is a parameter of the paint() function. This Graphics class provides painting functionality in the form of an applet. This technique is comparable to the Thread class’s runnable state.

 stop(): The stop() function is used to terminate the applet. Whenever the browser is closed, minimised, or the application crashes unexpectedly, it is called. After using the stop() function, we may use the start() method. This approach is mainly concerned with code cleanup. This function can be compared to the Thread class’s state of being blocked

 destroy(): When we have finished our applet work, we utilise the destroy() function to kill the application. It will only be used once. We can no longer start() the applet once it has been destroyed. This function is analogous to the Thread class’s dead state paint() method, which may be used to paint any shape, such as a square, rectangle, trapezium, eclipse, etc. The paint() method takes an argument called ClassGraphics. This Graphics class provides painting functionality in the form of an applet.

 Using an HTML file, implement the Applet Life Cycle in the following way:

Applet Life Cycle

 Wondering where to learn Java?

 upGrad’s Executive PG Program in Software Development is where your hunt ends!

 Key Highlights-

  • Top-Notch Faculty Members & Industry Experts
  • Free exclusive access to Data Science and Machine Learning
  • Option for no-cost EMI
  • 10 Programming Languages and Tools

 Conclusion

 Java is a highly significant programming Language that you must know if you are a software enthusiast. A course on this topic will definitely enhance your prospects as a software developer in the long run and open new avenues for a prosperous career.

What is the purpose of the applet class?

Any applet that is to be placed on a Web page or viewed by the Java Applet Viewer must be a subclass of the Applet class. The Applet class acts as a common interface among applets and their surroundings.

How many types of applets are there?

There are two types of applets: local applets and remote applets.

What is the difference between applet and application in Java?

The major distinction between an applet and an application is that an applet is a short Java programme that can be executed by a Java-compatible web browser, but an application is a standalone programme that can run directly on the machine.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

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

Our Best Software Development Course

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks