Written by Sai Sandeep Thota on November 2, 2013 in Java > Programming

Java Program to create Basic Applet

GET ALERTS:

Get our Latest updates delivered to your mailbox!

An Applet in Java is a simple program that runs in a web browser. They are useful in creating Web applications. They can transport over the internet from one computer to another and run using AppletViewer on any web browser that supports Java. An applet is just like any other application program, it can perform arithmetic operations, display graphics, play songs accept user inputs, create animations, handle events etc.,

Applet uses Applet class and Graphics class services. Applet class which is contained in Java Applet package provides life and behavior to the Applet. Through its methods such as init();, start();, destroy();, stop();, paint();.

Paint method is used to actually display the results on the console. The general syntax is:
public void paint(Graphics g)
paint(); method requires Graphic class, we are creating an object called g to Graphics class and using g.drawString to print.

In this tutorial we will create a Basic Applet.

How to Create an Applet in Java

#0. As discussed earlier we need to import two classes: applet and awt (Graphics).
#1. You need to inherit the Applet class.
#2. You will need paint(); method and Graphics object to print on the console.
General Syntax:
ob.drawString("Your String or Variable", 0, 20);
0, 20 in the above syntax are left-margin and top-margin respectively.
#3. You are done with applet file, Now you need to create a HTML file.
#4. Just embed your Applet *.class file which is generated after compiling your *.java file, in your HTML file by using the following code:
<applet code="yourApplet.class" width="400" height="600">

Java Program to create Basic Applet

Java Applet file

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

public class myApplet extends Applet {
	public void paint(Graphics g)
	{
			g.drawString("Programming Unit", 10, 400);
	}
}

applet_java_pu

HTML file

<html>
<body>
<applet code="myApplet.class" width="400" height="600">
</body>
</html>

applet_viewer

Download Source Code

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: