Java/Introduction to Applets

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Data Types, Variables,and Arrays
Operators
Packages, Classes, and Interfaces
Java Program
Modifiers
Control Statements
Exception Handling
Object Oriented Programming
Wrappers
Strings
Math
Arrays
Random Numbers
Date and Time
Regular Expressions
Java Collections
Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
RMI
Image, Audio, Video
GUI
Applets
* Introduction to Applets
* View Applet in a web browser
Internationalization
JDBC
Java and XML


The very basic definition by which we can have a rough idea about what applet is can be that "Applets are small applications which are transported over the internet server, install themselves automatically without any manual assistance and run as a part of web document". Applets provides some security features like once an applet is loaded on to your client machine from a server location it can make a connection only back to the originating server. That means applets originating from a server cannot make connections with other servers. Let us take a small example, yahoo.com has deployed an applet in one of it several pages. When we open the page containing applet it will be automatically download by the client machine. After downloading it will checked by the JVM whether the byte code for the applet is valid or not. If it is valid JVM will execute the applet. Once applet is in running state it tries to make a connection with cnn.com to fetch the news. Due to the security feature applet will not be able to make the connection with cnn.com. But yes it can make the connection with its originating server that is yahoo.com.

Since they run on the web or internet server they follow more of a client- server mechanism and because it runs even very big and complex applications on the client it very successfully executes them without any kind of threat from viruses or unauthorised access.

How Applets are different from Java Applications

We can broadly define an applet with these characteristic features:

1. Applets do not need a main( ) method.

2. Applets must be run under an applet viewer or a Java-compatible browser.

3. User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the interface provided by the AWT.


These applets once written are compiled in the same way as any other Java Programs. However, running a Simple Applet is done in a bit different manner and we have basically two ways by which we can execute the same:

1. We can execute the applet within a Java-compatible Web browser.

2. We can also execute the applet using an applet viewer, such as the standard SDK tool, appletviewer.

An applet viewer executes the applet in a window and it generally considered to be the fastest and easiest way to test the applet.

When the applet is complied it gets included as an HTML file with the help of Applet tag and it is then executed by a Java-Enabled web browser when it encounters the Applet Tag within the HTML file.

SimpleAppletExample.java


import java.applet.Applet;
import java.awt.Graphics;
 
public class SimpleAppletExample extends Applet{
 
  public void paint(Graphics g) 
  {
    g.drawString("Welcome to MeshPlex.org",20,20);   
  }
 
}

SimpleAppletExample.html

<applet code="SimpleAppletExample.class" 
        codebase="."
        width="600" height="95">
</applet>

Dont forget to compile the java class before openning the html code in a web browser. Keep the compiled java .class file and .html file in the same directory. Then open the html page in a web browser.

In general, we can quickly iterate through applet development by using the following three steps:

1. Edit a Java source file.

2. Compile the program.

3. Execute the applet viewer, specifying the name of the applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute the applet.

All the applets are subclasses of Applet. So, it becomes necessary to always import java.applet and since all these applications run in a window it becomes mandatory for us to import java.awt as it helps to get us support to run our applications in that window. Full form of AWT is Abstract Window Toolkit.

The Applet Class

Java.applet package contains the Applet Class. It contains various methods that help us to have complete control on the execution of our applet. The Applet class provides all necessary support like starting and stopping of an applet, providing methods that load and display images, methods which load and play the audio clip etc.

As we have mentioned in the above section that Applet extends the AWT class Panel which provides support to execute the application in the window based graphical interface. Panel extends Container, which extends Component and thus it supports all the window based activities.

Applet Architecture

The applet is a window based program and works on the event-driven architecture. It means that an applet waits until an event is occurred. As soon an event occurs the AWT (abstract window toolkit) intimates the applet by calling an event handler which the applet provides. You can also can them Callback methods.

Once this process is completed successfully the applet must take the appropriate action and return the control to the AWT. It should in no condition keep the control of the process for long with itself, rather in any situation wherein it has to perform the repetitive tasks it should immediately start an additional thread of execution to avoid getting into the above mentioned scenario.

In the process of execution of an applet it is mandatory that the user initiates the interaction with the applet in the form of an event. For example clicking on a button or on checkboxes also initiate an event to which the applet responds by following the procedure which we have discussed just above in this section. As with every event an event handler is generated by the applet.

Although the Applet Architecture is not very easy and simple to understand the Applets AWT architecture makes it quite simple by providing a much cleaner approach which is very quickly acquired.

Applet Skeleton

All the very commonly used applets are basically derived by overriding the set of methods which provide us the basic mechanism by which the browser or the applet viewer interfaces to the applet and controls its execution. Let’s prove the this written statement by considering the case of few methods which an applet uses:

init( ), start( ), stop( ), and destroy( ). These methods are defined by Applet.

Lets us discuss now how each of these methods shown in the applet skeleton actually works and what is each one of their role

Immediately, the moment an applet begins the AWT calls these methods in the following sequence: first the init () method is called and here we initialize the variables and this method is called only once during the run time of the applet, then the start ( ) method is called and it as its name suggest it restarts the applet after it has been stopped and this method is called each time an applet’s HTML document is displayed on the screen and finally and the paint ( ) method is called and it is called every time when we need the output to be drawn. This method has one parameter of type graphics. It describes the graphics environment is which the applet is actually running.

And at the time of terminating the applet it first calls stop ( ) method which closes the applet’s HTML document. this method basically stops all the threads which are executing at that point of time and are not required by the applet and finally the destroy ( ) method is called which makes sure that the applet which we have been executing can be removed completely from the memory and at this point of time we need to free all the pre occupied resources which the applet might be using.

Simple Applet Display methods: As we have been continuously stating that applets are displayed in a window which is supported by AWT to perform the input and output operations, we can use drawstring ( ) to output a string to an applet. The syntax for which is defined below:

void drawString(String message, int x, int y)


Where, message is the string to be output beginning at x ,y.

To set the background colour for an applet’s window we should use setBackground ( ) Method, the syntax for this is:

void setBackground(Color newColor)

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
 
public class AppletSetBackgroundExample extends Applet {
 
	public void paint(Graphics g) {
 
		// Color is defined using RGB. // R - Red, G - Green, B - Blue.
		// These are primary colors and other color can be drived 
		// through the right combination of these. Let us say we 
		// want a green background. Value range is 0-255.
		Color color = new Color(0, 255, 0);
		setBackground(color);
	}
}

Image:Applet.jpg

And to set the foreground use setForeground ( ) method. The syntax for this is:

void setForeground(Color newColor)

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
 
public class AppletSetBackgroundExample extends Applet {
 
	public void paint(Graphics g) {
 
		// Color is defined using RGB. // R - Red, G - Green, B - Blue.
		// These are primary colors and other color can be drived
		// through the right combination of these. Let us say we
		// want a green background. Value range is 0-255.
 
		Color bgcolor = new Color(0, 255, 0); // green
 
		Color border = new Color(0, 0, 0); // black
 
		Color fgcolor = new Color(255, 0, 0); // red
 
		setBackground(bgcolor);
		setForeground(fgcolor);
		g.draw3DRect(20, 20, 200, 100, true);
		g.drawString("MESHPLEX", 90, 70);
	}
}

Image:Applet-foreground-color.jpg

Repaint

Till now we have fully understood that an applet can only write on its window when the AWT calls the update ( ) or paint ( ) method, but if this is the scenario we have one more thing to consider that how will the applet be able to update its window when its information changes.

This is basically done due to the phenomena that the applet is never expected to keep the control in its own hand for a longer period rather it should immediately transfer the control to AWT run time system and it is not allowed to create a loop in the paint ( ) method and for this the problem is solved by calling repaint( ) method which is again defined by AWT.

It causes the AWT rum time system to execute a call to the applet’s update ( ) method which as default calls the paint ( ) method so for another aprt of the applet to give the output we need simply to store the output and tehn call repaint ( ) method and then the AWT will execute a call to paint ( ) which will display the stored information.

This repaint( ) method which we are talking about has four forms. We will take each one of them here now :

1. The simplest version of repaint( ) is shown here:

void repaint( ): It causes the entire window to be repainted.

2. This will specify a region that will be repainted:

void repaint(int left, int top, int width, int height) THE JAVA LIBRARY Where , the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region are passed in width and height. These dimensions are specified in pixels.

3. void repaint(long maxDelay)

4. void repaint(long maxDelay, int x, int y, int width, int height)

Where, maxDelay specifies the maximum number of milliseconds that can elapse before update ( ) is called.

Previous Next