JAVA PROGRAMMING

 

APPLETS

 Applet Fundamentals:

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

 Applet Basic:

All applets are subclasses of Applet class. Thus, all applets must import java.applet. Applets must also import java.awt. AWT stands for the Abstract Window Toolkit. Since all applets run in a window, it is necessary to include support for that window. Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser or an appletviewer.

Execution of an applet does not begin at main( ). Actually, few applets even have main() methods. Instead, execution of an applet is started and controlled with an entirely different mechanism. Output to your applet's window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X, Y location. Input is also handled differently than in an application.

Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag. This way, your code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting the applet viewer with your Java source code file specified as the target. Here is an example of such a comment:

/* < applet code="MyApplet" width=200 height=60 > < / applet> */

 

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier.

AppletViewer:

An applet is run usually inside a web browser, such as HotJavaTM or the Netscape Navigator or Internet Explorer, which are capable of running Java software programs. To simplify and speed up development, the Java 2 comes with a tool designed only to view applets, not HTML pages. This tool is the appletviewer.

The appletviewer is a Java application that enables you to run applets without using a Web browser. It resolves a minimum browser. The appletviewer reads the HTML file specified by the URL on the command line. This file must contain the instructions for loading and running one or more applets. The appletviewer ignores all other HTML codes. It does not display normal HTML or embedded applets in a text page. The appletviewer posts a frame - like space onto the screen, instantiates an instance of the applet, and post that applet instance to the frame.

Applet Programming:

An applet program differs in its style and behaviour from a normal application program. A normal application program is executed at the command prompt. An applet is graphical; window based and works on the World Wide Web.

Writing an applet program:

 import java.applet.*;
import java.awt.*;
               public class Hello extends Applet{
               public void paint(Graphics g){
                               g.drawString ("Truth",20,100);
                               g.drawString ("Peace", 40,130) ;
                               g.drawString("Integrity", 60,160) ;
               }
               }
 

Let us analyze the code.

Line 1
This line imports applet-related methods into your program.

Line 2
Since an applet is window based, it also requires methods to create and manage window-related activities. This statement will include window-related methods for the applet. Abstract Window Toolkit (AWT) provides all the graphical support for this window. AWT contains various classes and methods that provide us the GUI features.

Line3
This is the name of the program. Every applet program extends from its super class 'Applet'.

Line 4
This is the method, which is responsible for painting the three words on the applet window. paint( ) takes a 'Graphic' parameter 'g'.

The paint( ) method is called automatically when the Component (in this case, the applet) decides that it needs to update itself - perhaps because it is being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over the Web browser. The applet calls its update( ) method (defined in the base class), which goes about restoring everything, and as a part of that restoration calls paint( ). You don't have to override paint( ), but it turns out to be an easy way to make a simple applet.

When update( ) calls paint( ), it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because you're limited to the surface of that particular component and thus cannot paint outside that area, which is a good thing or else you'd be painting outside the lines. In the case of an applet, the surface is the area inside the applet.

The Graphics object also has a set of operations, which revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc. There are some methods that allow you to draw characters, however, and the most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet's drawing surface. This location is given in pixels, so it will look different on different machines, but at least it's portable.

Line 5
g.drawString( ) method is the equivalent of System.out.println( ). The drawString( ) method prints the given string. But the difference here is that the applet runs on a window. So, you must specify the position where you want the string to be printed. Here, the statement prints the string 'Truth'at 20, 100.

The applet window is made of pixels. These pixels are arranged in the row/column fashion. If you want to print in an applet, you have to specify the row and column position of the applet window.

Line 6 and Line 7
prints the words 'Peace' and 'Integrity' at the positions 40,130 and 60,160 respectively.

Save this file as Hello.java.

Testing an applet:

Once compiled using 'javac', applets are tested either on a browser or through an appletviewer. (In this case we will use browser since we have not included Applet tag in the Java program).

An applet cannot be executed like a normal Java program. Since applets are used in the Web, they are embedded in a Web page. You will have to either create a new Web page or use an existing Web page to view an applet. < applet > tag should be used inside an HTML file to invoke the applet class file.

For the above applet program (Hello) the tags can be used in the following manner.

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

The 'code' attribute invokes the Java class file. The 'width' and 'height' attributes define the
size of the applet window in the Web page.

For testing purposes, applets can be viewed through a program called Appletviewer. The appletviewer can be executed directly from the command line along with the html file name.

To state an example, if the

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

is included in a file Hello.html, it will be executed in the following manner .

C:\>AppletViewer test.html

Working with colors:

AWT offers various methods to add colors to the applets. The AWT color system allows you to specify any color. To set the background color of an applet's window, setBackground( ), method and setForeground( ) to set fore ground of the applet.

 
 
               // Program to demonstrate color setting
               import java.applet.*;
               import java.awt.*;
 
               public class AppleColor extends Applet{
                               public void init( ) {
                                              setBackground(Color.green);
                                              setForeground(Color.red);
                               }
                               public  void paint( Graphics g) {
                                              g.drawString("Apple",20,100);
                                              g.setColor(Color.yellow);
                                              g.drawString("Banana",40,130);
                                              g.setColor(Color.orange);
                                              g.drawString("Orange",60,100);
                               }
               }
 

The init( ) method is added to the code to initialize the foreground colors. The setBackground( ) statement sets the background color of the applet to yellow. The setForeground( ) methods sets the initial foreground color to red.

The following color constants can be used along with 'Color' class to set the colors.

Color.black       Color.magenta       Color.blue        Color.orange       Color.cyan Color.pink         Color.darkGray         Color.red         Color.gray Color.white          Color.green          Color.green         Color.yellow         Color.lightGray      

Applet Skeleton:

All but the most trivial applets overrides a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods - init( ), start( ), stop( ) and destroy( ) - are defined by Applet. Another method, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. These five methods can be assembled into the skeleton shown here:

 // An Applet skeleton.
 
import java.awt.*;
import java.applet.*;
 
/*  < applet code="AppletSkel" width=300 height=100>
    < / applet>*/
 
               public class AppletSkel extends Applet {
               //Called first.
               public void init( ) {
               // initialization
               }
 
 
/* Called second, after init( ) .Also called whenever the applet is restarted. */
                public void start( ) {
                               // start or resume execution
               }
// Called when the applet is stopped.
 
                public void stop( ) {
               // suspends execution
               }
 
// Called when applet is terminated. This is the last method executed.
               public void destroy( ) {
               // perform shutdown activities
               }
 
//Called when an applet's window must be restored.
               public void paint (Graphics g) {
               // redisplay contents of window
               }
               }
 

Although this skeleton does not do anything, it can be compiled and run. When run, it generates the following window when viewed with an applet viewer:

Applet Initialization and Termination:

It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the AWT calls the following methods, in this sequence:

  1. init( )
  2. start( )
  3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

  1. stop( )
  2. destroy( )

init( ): The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

start( ): The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once-the first time an applet is loaded - start( ) is called each time an applet's HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( ): The paint( ) method is called each time your applet's output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet required.

stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the applet - when it goes to another page, for example. When stop() is called, the applet is probably running. You should use stop( ) to suspend threads that don't need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.

destroy( ): The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

Overriding update( ): In some situations, your applet may need to override another method defined by the AWT, called update( ). This method is called when your applet has requested that a portion of its window be redrawn. The default version of update( ) first fills an applet with the default background color and then calls paint( ). If you fill the background using a different color in paint( ), the user will experience a flash of the default background each time update( ) is called-that is, whenever the window is repainted. One way to avoid this problem is to override the update( ) method so that it performs all necessary display activities. Then have paint( ) simply call update( ). Thus, for some applications, the applet skeleton will override paint( ) and update( ), as shown here:

public void update(Graphics g) {
// redisplay your window, here.
}

public void paint (Graphics g) {
update(g);
}

Passing Parameters:

HTML tag is the place from where we can send the parameters. Parameters are an easy way to configure Java applets without actually changing the source file.

< param > tag is used with < applet > to send the parameters to the applet classes. e.g.

< applet code = Hello.class width = 300 height = 200>
< param name = "colour" value = "green"> < / applet>

How does the Java applet accept the value and utilise it inside the program once the parameter has been passed from the HTML file?

getParameter( ) method is used to retrieve the parameter value inside the program. The value returned by the parameter will be of String type. Thus, for numeric data types, you must convert them into their internal formats. If no parameters are sent, the getParameter( ) method returns a null value.

The following code tells you about passing parameters and handling the same in the Java code. The HTML file passes the two values, 'principal' and 'period' to the Java class. The Java code uses these values, calculates the simple interest and prints the same along with the passed values.

 The HTML File
 
         < applet code = "SI" width = 300 height = 100>
        < param name = principal value = 25000>
        < param name = period value = 7>
        < / applet>
 
 
Save this as SI.html
 
The Java code
 
import java.awt.*;
import java.applet.*;
               public class SI extends Applet {
               public void init( ) (
                               setBackground(Color.yellow) ;
                               setForeground(Color.blue) ;
                               int pAmt, term;
                               double rate, si; rate = 12;
 
               public void start( ) {
                               String data = null;
                               data = getParameter("principal");
                               if(data!= null)
                                              pAmt  = Integer.parseInt(data);
                               else
                                              pAmt = 0;
 
// Over writing data value with period
                               data = getParameter("period");
                               if(data !=null)
                                              term = Integer.parseInt(data);
                               else
                                              term = 0;
 
                               si = (pAmt * rate * term) /100;
               }
               public void paint(Graphics g) {
                               g.drawString("The principle amount  :"+pAmt,10,20);
                               g.drawString("No of Years :"+term, 10,50);
                               g.drawString("S I at 12%   :"+s1,10,80);
                               }
               }
 

Event Handling:

Event handling is at the core of successful applet programming. Most events to which your applet will respond are generated by the user. These events are passed to your applet in a variety of ways, with the specific method depending upon the actual event. There are several types of events. The most commonly handled events are those generated by the mouse, the keyboard, and various controls, such as a push button. Events are supported by the java.awt.event package.

 Events:

In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. You are free to define events that are appropriate for your application.

 Event Sources:

A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener(). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them. Some sources may allow only one listener to register.

 Event Listeners:

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receives and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

 Capturing an Event:

There are various user - triggered events that Windows handles, viz., pressing a key, loading a document, holding a mouse button, typing some text, etc. There are some events that take place without the user's intervention. These events happen due to an internal signal passed on by the program, viz., loading an HTML page, opening a database, etc.

Windows works by handling, responding to, and processing events. So does Windows programming. Since applets are designed in the Windows-based coding style and rely on AWT for external support, they also work based on events. As you are aware, no applet holds the control of a program. It is the AWT that does so.

The applet need not be concerned about the events as long as the AWT is in place. AWT has its default response to all the events. If the programmer wishes to perform any action other than the default stated by the AWT, he/she must capture the events and perform an alternate task using his/her own method.

When you try to capture a mouse event and redirect it to a method, it calls the method by sending three parameters - the event object, the x coordinate and the y coordinate of the mouse pointer. For keyboard events, the method is called with two parameters, viz., the event object and the Unicode of the key pressed.

 

 Mouse Events:

The following are the mouse events provided by AWT:

mouseDown(evtobj, x, y) : This method is called when a mouse button is pressed. The event object is sent automatically and the screen position where the mouse button is pressed is sent to the method.

mouseDrag(evtobj, x, y) - It is called when a mouse button is pressed and dragged.

mouseEnter(evtobj, x, y) - It is called when a mouse moves into the window.

mouseExit(evtobj, x, y) - It is called when the mouse goes out of the window.

mouseMove(evtobj, x, y) - It is called when the mouse is moved.

mouseUp(evtobj, x, y) - It is called when the mouse button is released.

The following program demonstrates the usage of the mouse events. It loads the applet window, and waits for a mouse event to occur. When a mouse button is pressed, the method gets activated and displays a message on the applet screen.

import java.applet.*;
import java.awt.*;
/* < applet code=Demo width = 200 height=200>
    < / applet>         */
               public class Demo extends Applet {
                               int xcord = 0;
                               int ycord = 0;
                               String msg;
               public void init( ){
                               setBackground(Color.green);
                               setForeground(Color.red);
               }
               public boolean mouseDown(Event obj, int x, int y) {
                               xcord = x;
                               ycord = y;
                               msg = "Arts is I, Scince is WE";
                               repaint ( );
                               return true;
               }
               public boolean mouseMove(Event obj, int x, int y) {
                               showStatus("Mouse Position "+x+","+y);
                               return true;
               }
               public void paint(Graphics g){
                               g.drawString(msg, xcord, ycord);
               }
               }
  Keyboard Events: 

The keyboard also generates some events, like the mouse. These events involve the user to pressing a key, releasing key, etc.

There are two essential event methods that are offered for tackling the mouse events.

keyDown( evtobj, KEY)       - Called when a key is pressed.

keyUp( evtobj, KEY)        - Called when a pressed key is released.

The variable KEY contains the Unicode character number of the pressed key. But, it does not store special keys that are spread beyond the Unicode boundary. For instance keys like F1, F2, F3, Page Down, etc., are not traced by the variable KEY. You can trace special keys like F1, F2, F3 or navigation keys like Page Down, left arrow etc., using event object class. Event object is a class that carries all the information about an event. For instance evtobj.F1, evtobj.F2 etc., The following program demonstrate few of this key constants in action.

 // Program to demonstrate some keyboard events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
 
/* < applet code="KeyEvents" width=300 height=100>
   < / applet> */
 
public class KeyEvents extends Applet implements KeyListener{
               String msg="";
               int X=10,Y=20;
               public void init( ){
                               addKeyListener(this);
                               requestFocus( );
               }
 
               public void keyPressed(KeyEvent ke){
                               showStatus("Key Down");
 
                               int key=ke.getKeyCode();
                               switch(key) {
                                              case KeyEvent.VK_F1:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_F2:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_F3:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_PAGE_DOWN:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_PAGE_UP:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_LEFT:
                                                             msg +="";
                                                             break;
                                              case KeyEvent.VK_RIGHT:
                                                             msg +="";
                                                             break;
                                              }
                               repaint( );
               }
 
               public void keyReleased(KeyEvent ke){
                               showStatus("Key Up");
               }
 
               public void keyTyped(KeyEvent ke){
                               msg +=ke.getKeyChar();
                               repaint(  );
               }
 
               public void paint(Graphics g){
                               g.drawString(msg, X, Y);
               }
}
 
// program to demonstrate mouse event
 
import java .awt .* ;
import java.applet.*;
 
               public class mouse extends Applet {
                               String str = " ";
                               int mouseX = 0, mouseY = 0;
 
               public void init( ) {
                               setBackground(Color.pink);
                               setForeground(Color.red);
               }
 
               pub1ic boolean mouseDown(Event evtObj, int x, int y) {
                               mouseX = x;
                               mouseY = y;
                               str = "Mouse is Down" ;
                               repaint( ) ;
                               return true;
               }
 
               public boolean mouseUp(Event evtObj, int x, int y) {
                               mouseX = x;
                               mouseY = y;
                               str = "Mouse is Up" ;
                               repaint( ) ;
                               return true;
               }
 
               public boolean mouseMove(Event evtObj, int x, int y) {
                               showStatus ("Mouse Position: " + x + " : " + y) ;
                               return true;
               }
 
               public boolean mouseDrag(Event evtObj, int x, int y) {
                               mouseX = x;
                               mouseY = y;
                               str = "Do not drag, leave me alone";
                               showStatus("Mouse dragging at:" + x + ":" + y) ;
                              repaint( ) ;
                               return true;
               }
 
               public void paint(Graphics g) {
                               g.drawString(str, mouseX, mouseY) ;
               }
}
 
 Inter - Applet Communication: 

There could be more than one applet in some sites. An entry made in one-applet influences the content of the other applet. This is possible when applet communicates with each other in the background.

Inter - applet communication is possible between applets that share the same web page within the same browser. Though applet communication is being used very effectively in sites, it is totally browser - dependent.

getDocumentBase( ) and getCodeBase( ):

Often, you will create applets that will need to explicitly load media and text. Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base) and the directory from which the applet's class file was loaded (the code base). These directories are returned as URL (uniform resource locators) objects by getDocumentBase( ) and getCodeBase( ). They can be concatenated with a string that names the file you want to load. To actually load another file, you will use the showDocument( ) method defined by the AppletContext interface.

                // program to demonstrate getDcoument( ) and getDocumentBase( )
               import java.awt.*;
               import java.applet.*;
               import java.net.*;
               /* < applet code= "Bases" width=300 height = 50>
                   < / applet> */
 
               public class Bases extends Applet {
                               public void pant( Graphics g) {
                                              String msg;
 
                                              URL myurl = getCodeBase( );
                                              msg =     "Code base: "+myurl.toString( );
                                              g.drawString(msg, 10, 20);
 
                                              myurl = getDocumentBase( );
                                              msg = "Document base: "+myurl.toString( );
                                              g.drawString(msg, 10, 20);
                               }
               }
 AppletContext & showDocument( ): 

One application of Java is to use active images and animation to provide a graphical means of navigating the web that is more interesting than the underlined blue words used by hypertext. To allow your applet to transfer control to another URL, you must use the showDocument( ) method defined by the AppletContext interface.

AppletContext is an interface that lets you get information from the applet's execution environment. The context of the concurrently executing applet is obtained by a call to the getAppletContext( ) method defined by Applet. Within an applet, once you have obtained the applet's context, you can bring another document into view by calling showDocument( ). This method has no return value and throws no exception if it fails. There are two showDocument( ) methods. The methods showDocument(URL) displays the document at the specified URL. The method showDocument(URL,where) displays the specified document at the specified location within the browser. Valid arguments for where are "- self" (show in parent frame), "- top" (shown in topmost frame), and "- blank" (show in new browser window). You can also specify a name, which causes the document to be shown in a new browser window by that name.

The following applet demonstrate AppletContext and showDocument( ). Upon execution it obtains the current applet context and uses that context to transfer control to a file called Test.html. This file must be in the same directory as the applet. Test.html can contain any valid hypertext that you like.

 
               import java.awt.*;
               import java.applet.*;
               import java.net.*;
 
               /* < applet code ="ACDemo" width = 300 height=50>
                   < / applet> */
 
               public class ACDemo extends Applet {
                               public void start( ) {
                                      AppletContext ac = getAppletContext( );
                                      URL url = getCodeBase( );
 
                               try {
                                        ac.showDocument (new URL(url + "Test.html"));
                                        } catch(MalformedURLException e) {
                                              showStatus("URL not found");
                                        }
                               }
               }
 

We will create two applets that communicate with each other in the same Web page. Begin by creating the first applet (First.java), which has a button displayed on its window. This applet sends the communication to the second applet.

 
 
               import java.awt.*;
               import java.applet.*;
               public class First extends Applet{
                               Button bl;
               public void init( ){
                               setBackground(Color.red) ;
                               bl = new But ton ("New Year") ;
                               add(bl) ;
               }
 
               public boolean action(Event evt,Object obj) {
                               if(evt.target instanceof Button) {
                                       Applet receiver = getAppletContext( ) 
.getApplet( "customer");
                                       return receiver.action(evt,obj) ;
                              }
               return super. action (evt,obj) ;
               }
               }
 

The init( ) method sets the background colour , creates a button and adds it to the applet window. The 'if' expression looks for the command button to see whether it was clicked. If the button was clicked, the method uses getAppletContext( ). getApplet( ) to receive the applet 'Second' and store it into variable 'receiver', using the name 'customer'. It sends the event to the 'Second' applet in the following line so that it can handle it.

The second applet receives the event from the applet.
 
import java.awt.*;
import java.applet.*;
               public class Second extends Applet{
                               Label msg;
               public void init( ){
                               setBackground(Color.yellow) ;
                               msg = new Label ( "wai ting for the message " );
                               add (msg) ;
               }
               public boolean action(Event evt,Object obj){
                               if("New Year".equals(evt.arg)){
                                       msg.setText("Wishing you a Very Happy New Year");
                                       return true;
                               }
               return super.action(evt,obj) ;
               }
               }
 

This init( ) method sets the background colour and creates a label called 'msg' with an initial label 'waiting for the message'. The action( ) method includes an 'if' expression, which checks to see whether the event being passed to it has an argument that is the label for the button in the applet 'First'. In response to this it will change the 'msg' label to display the greeting on the window.

 The fileInter-applet.html calls both applets on to Web page. It has two applet tags.
 
               < Applet code = "Frist.class" width = 200 height = 100>
               < / Applet>  
               < Applet code= "Second.class" width = 200 height = 100 
name =  "customer">
               < / Applet>
 

There are two important things you must do for implementing inter-applet communication they are:

  • Use the getAppletContext( ) method to retrieve information about the other applet you want to connect with.
  • Handle events in such a manner that when an event is passed to an applet, it can be passed to the other applet.
 
 
// Example program
               import java.applet.*;
               import java.awt.*;
 
               /* < applet code=" SimpleEvent" width=300 height=300>
                  < / applet> */
               public class SimpleEvent extends Applet {
 
         String msg[]={"Click here for today's messages","Never forget a lesson you
                               learnt","I is Arts, We is Science","Save green, to be clean"};
                Color c[ ] = {Color.red,Color.blue,Color.cyan,Color.green};
                int i=0;
 
               public void init( ){
                               setBackground(Color.yellow);
                               setForeground(Color.red);
               }
 
               public boolean mouseDown (Event obj, int x, int y){
                if(i==4)
                  i=0;
                repaint( );
                return true;
               }
 
               public void paint(Graphics g)
               {
                               g.drawString("Applet, apple of Java's eye",10,50);
                               g.setColor(c[i]);
                               g.drawString(msg[i],50,150);
                               i++;
               }
}
                   
 

 

 

 

  HOME

<<PREVIOUS             NEXT>>

Want Easy lessons and exercises!! Then search here:

Google
Web www.poombatta.com



© poombatta.com