Monday, January 27, 2020

Java Applets

Applets

Java applets are small programs or snippets those can be embedded into a web page, can be transported over internet, can run inside a browser(or some other application), can be downloaded by the users, provides a rich environment for web applications and usually pretend to run at their own. We generally provide some user interface to users to interact with Applets. We can run Applets either by a special program known as Applet Viewer or inside some browser. The browser must have Java plug-in to manage the life cycle of the Applet.

Java Applets can perform following events in its life cycle

  • Initialize itself (init() method)
  • Start itself (start() method)
  • Stop itself (stop() method)
  • Destroy itself (destroy() method)

Your Applet class must be the subclass of an Applet. The Applet class specifies a standard interface between applets and their environment. Java Applets are now becoming obsolete now, as the latest versions of Java are discontinuing support for Applets.

Example

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
//Applet class
public class MyApplet extends Applet{

    @Override
    public void destroy() {//clean the object from memory
       
        super.destroy();
        System.out.println("destroyed");
    }

    @Override
    public void init() {//Initialize the object
       
        super.init();
        System.out.println("initialized");
    }

    @Override
    public void start() {//Start executing
       
        super.start();
        System.out.println("started");
    }

    @Override
    public void stop() {//Stop executing
       
        super.stop();
        System.out.println("stopped");
    }

    @Override
    public void paint(Graphics g) {//Let's draw something over screen
        g.setColor(Color.BLUE);
        g.drawLine(10, 15, 300, 500);
        g.drawLine(500, 300, 15, 10);
        g.drawString("Welcome to Applet", 100, 100);
    }  
}

Video Tutorial: