Unitvi Concepts of Applets differences between applets and

Unit-vi

• Concepts of Applets, differences between applets and Applications • Life cycle of an applet • Types of applets, • creating applets, • passing parameters to applets

What is an applet? Applet: A small Java program that can be inserted into a web page and run by loading that page in a browser. An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Javacompatible web browser. 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.


Applet classes in Java java. lang. Object java. awt. Component java. awt. Container java. awt. Panel java. applet. Applet javax. swing. JApplet

How Applets Differ from Applications Although both the Applets and stand-alone applications are Java programs, there are certain restrictions are imposed on Applets due to security concerns: – Applets don’t use the main() method, but when they are loaded, automatically call certain methods (init, start, paint, stop, destroy). – They are embedded inside a web page and executed in browsers. – Takes input through Graphical User Input ( GUI ). – They cannot read from or write to the files on local computer. – They cannot run any programs from the local computer. The above restrictions ensures that an Applet cannot do any damage to the local system.

1. Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading. 2. Applets can only be executed inside a java compatible web browser or appletviewer whereas Applications are executed at command line by java. 3. After an applet arrives on the client, it has limited access to resources on local computer. Applications have no restriction to access resources. 4. Applets don’t have the main() method as in applications. Instead they operate on an entirely different mechanism where they are initialized by init(), started by start(), stopped by stop() or destroyed by destroy(). 5. A Java Applet is made up of at least one public class that has to be subclasses from java. applet. Applet. Whereas, A Java application is made up of a main() method declared as public static void that accepts a string array argument, along with any other classes that main() calls.

Life cycle of an Applet Begin init() Born start() stop() Running paint() Idle start() destroy() Dead End

Life cycle of an Applet It is important to understand the order in which these methods are called. When an applet is started , the following sequence of method calls takes place: 1. init( ) 2. start( ) 3. paint( ) When an applet is terminated, the following sequence of method calls takes place: 1. stop( ) 2. destroy( )

Applet States Initialisation 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. Running – more than once The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. It is called each time an applet’s HTML document is displayed on screen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ). Display – more than once paint() happens immediately after the applet enters into the running state. It is responsible for displaying output. paint( ) is also called when the applet begins execution. The paint( ) method is called each time your applet’s output must be redrawn. The paint( ) method has one parameter of type Graphics.

Idle The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page. Dead/Destroyed State – only once 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( ).

Building Applet Code: An Example import java. awt. *; import java. applet. Applet; public class Simple. Applet extends Applet { public void paint(Graphics g) { g. draw. String (“A Simple Applet", 20); } } Begins with two import classes. java. awt. * -- required for GUI java. applet. * -- every applet you create must be a subclass of Applet, which is in java. applet package. The class should start with public, because is accessed from outside.

Contd. . ØApplets do not begin execution at main(). ØAn applet begins its execution when the name of its class is passed to an applet viewer or to a java compatible browser. ØCompile the applet in the same way that we have been compiling programs. ØRunning an applet involves a different process.

Running an Applet �There are two ways in which you can run an applet: ØExecuting the applet within a Java-compatible browser. ØUsing a tool called , appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

Executing in a web browser. To execute an applet in a web browser, you need to write a short HTML file that contains a tag ( Applet ) that loads the applet. HTML file that contains a Simple. Applet <APPLET code=“Simple. Applet“ width=400 height=300> </APPLET> Save the file with. html extension (Example: Simple. html) After you create this file, open your browser and then load this file, which causes Simple. Applet to be executed. width and height specify the dimensions of the display used by the applet.

Executing by using appletviewer There are two ways 1. Use earlier html page, which contains applet tag, then execute by using following command. C: >appletviewer htmlfilename. html 2. Include a comment at the beginning of your source code file that contains the applet tag, then start applet viewer with your java source code file. C: >appletviewer Simple. Applet. java import java. awt. *; import java. applet. Applet; /* <applet code=“Simple. Applet” width=200 height=60 ></applet> */ public class Simple. Applet extends Applet { public void paint(Graphics g) { g. draw. String (“A Simple Applet", 20); } }

Four of these methods init(), start(), stop(), and destroy() are defined by Applet. Another, paint() is defined by the AWT Component class. Although the above program does not do anything, it can be compiled and run.

Structure of an applet // An Applet. Structure import java. awt. *; import java. applet. *; /* <applet code="Applet. Structure" width=300 height=100> </applet> */ public class Applet. Structure 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 whenever an applet's output must be redisplayed. public void paint(Graphics g) { // redisplay contents of window } }

Creating Applets /* A simple applet that sets the foreground and background colors and outputs a string. */ import java. awt. *; import java. applet. *; /* <applet code="Sample" width=300 height=50> </applet> */ public class Sample extends Applet{ String msg; public void init() { // set the foreground and background colors. set. Background(Color. cyan); set. Foreground(Color. red); msg = "Inside init( ) --"; } public void start() { // Initialize the string to be displayed. msg += " Inside start( ) --"; } public void paint(Graphics g) { // Display msg in applet window. msg += " Inside paint( ). "; g. draw. String(msg, 60, 40); } }

Passing Parameters to Applet ØThe APPLET tag in HTML allows you to pass parameters to your applet. ØTo retrieve a parameter, use the get. Parameter( ) method. Ø It returns the value of the specified parameter in the form of a String object.

Applet Program Accepting Parameters import java. applet. Applet; import java. awt. *; /* <APPLET CODE="Hello. Applet. Msg" width=500 height=400> <PARAM NAME="Greetings" VALUE="Hello Friend, How are you? "> </APPLET> */ public class Hello. Applet. Msg extends Applet { String msg; public void init(){ msg = get. Parameter("Greetings"); if( msg == null) msg = "Hello"; This is name of parameter specified in PARAM tag; } This method returns the value of paramter. public void paint(Graphics g) { g. draw. String (msg, 100); } }

Types of applets There are two types of applets: First is based on the Applet class These applets use the AWT to provide the GUI. This style of applet has been available since java was created. It is used for simple GUI’s. The second is based on the Swing class JApplet. These applets use the Swing classes to provide the GUI. Swing offers a richer and easy to use interface than AWT. Swing based applets are more popular.

Simple Swing Application import java. awt. *; import javax. swing. *; public class myjframe extends JFrame{ myjframe(){ Container content. Pane = get. Content. Pane(); JLabel jl=new JLabel("swing more powerful than AWT"); content. Pane. add(jl); set. Size(250, 250); set. Visible(true); } public static void main(String arg[]){ new myjframe(); } }

The methods defined by Applet • String get. Parameter(String param. Name) Returns the parameter associated with param. Name. null is returned if the specified parameter is not found. • void show. Status(String str) Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place. • URL get. Code. Base( ) Returns the URL associated with the invoking applet. • URL get. Document. Base( ) Returns the URL of the HTML document that invokes the applet.

The HTML APPLET Tag The syntax for the standard APPLET tag is shown here. Bracketed items are optional. < APPLET [CODEBASE = codebase. URL] CODE = applet. File [ALT = alternate. Text] [NAME = applet. Instance. Name] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = Attribute. Name VALUE = Attribute. Value>] [< PARAM NAME = Attribute. Name 2 VALUE = Attribute. Value>]. . . [HTML Displayed in the absence of Java] </APPLET>

void set. Background(Color new. Color) void set. Foreground(Color new. Color) Here, new. Color specifies the new color. The class Color defines the constants shown here that can be used to specify colors: Color. black Color. magenta Color. blue Color. orange Color. cyan Color. pink Color. dark. Gray Color. red Color. gray Color. white Color. green Color. yellow Color. light. Gray For example, this sets the background color to green and the text color to red: set. Background(Color. green); set. Foreground(Color. red); A good place to set the foreground and background colors is in the init( ) method. You can obtain the current settings for the background and foreground colors by calling get. Background( ) and get. Foreground( ), respectively. They are also defined by Component and are shown here: Color get. Background( ) Color get. Foreground( )

• Audio. Clip get. Audio. Clip(URL url, String clip. Name) Returns an Audio. Clip object that encapsulates the audio clip found at the location specified by url and having the name specified by clip. Name. • Image get. Image(URL url, String image. Name) Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by image. Name. • void play(URL url, String clip. Name) If an audio clip is found at the location specified by url with the name specified by clip. Name, the clip is played.

8). Design the user screen as follows and handle the events appropriately.

import java. awt. *; import java. awt. event. *; public class Add. Window extends Frame implements Action. Listener{ Label l 1, l 2, l 3; Text. Field t 1, t 2, t 3; Button b 1, b 2, cl; Add. Window(){ super("add window"); //setting the size of the window set. Size(250, 400); l 1=new Label("First Number : "); l 2=new Label("Second Number: "); l 3=new Label("RESULT : "); t 1=new Text. Field(10); t 2=new Text. Field(10); t 3=new Text. Field(10); b 1=new Button("add b 2=new Button("subtract "); cl=new Button("clear"); //setting the layout of the container window set. Layout(new Flow. Layout());

//adding the controls to the container window add(l 1); add(t 1); add(l 2); add(t 2); add(l 3); add(t 3); add(b 1); add(b 2); add(cl); b 1. add. Action. Listener(this); b 2. add. Action. Listener(this); cl. add. Action. Listener(this); if(ae. get. Source()==b 2) { int subtract=n 1 -n 2; t 3. set. Text(subtract+""); } if(ae. get. Source()==cl) { t 1. set. Text(""); t 2. set. Text(""); t 3. set. Text(""); } }//action. Performed method set. Visible(true); } public void action. Performed(Action. Event ae){ int n 1=Integer. parse. Int(t 1. get. Text()); int n 2=Integer. parse. Int(t 2. get. Text()); if(ae. get. Source()==b 1) { int add=n 1+n 2; t 3. set. Text(add+""); } public static void main(String args[]) { new Add. Window(); }//main method }//class

Handling Mouse Events using Applets // Demonstrate the mouse event handlers. import java. awt. *; import java. awt. event. *; import java. applet. *; /* <applet code="Mouse. Events" width=300 height=100> </applet>*/ public class Mouse. Events extends Applet implements Mouse. Listener, Mouse. Motion. Listener { String msg = ""; int mouse. X = 0, mouse. Y = 0; // coordinates of mouse public void init() { add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); }

// Handle mouse clicked. public void mouse. Clicked(Mouse. Event me) { // save coordinates mouse. X = 0; mouse. Y = 10; msg = "Mouse clicked. "; repaint(); } // Handle mouse entered. public void mouse. Entered(Mouse. Event me) { // save coordinates mouse. X = 0; mouse. Y = 10; msg = "Mouse entered. "; repaint(); } // Handle mouse exited. public void mouse. Exited(Mouse. Event me) { // save coordinates mouse. X = 0; mouse. Y = 10; msg = "Mouse exited. "; repaint(); }

// Handle button pressed. public void mouse. Pressed(Mouse. Event me) { // save coordinates mouse. X = me. get. X(); mouse. Y = me. get. Y(); msg = "Down"; repaint(); } // Handle button released. public void mouse. Released(Mouse. Event me) { // save coordinates mouse. X = me. get. X(); mouse. Y = me. get. Y(); msg = "Up"; repaint(); } // Handle mouse dragged. public void mouse. Dragged(Mouse. Event me) { // save coordinates mouse. X = me. get. X(); mouse. Y = me. get. Y(); msg = "*"; show. Status("Dragging mouse at " + mouse. X + ", " + mouse. Y); repaint();

// Handle mouse moved. public void mouse. Moved(Mouse. Event me) { // show status show. Status("Moving mouse at " + me. get. X() + ", " + me. get. Y()); } // Display msg in applet window at current X, Y location. public void paint(Graphics g) { g. draw. String(msg, mouse. X, mouse. Y); } }

/*Week 7 : Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -, *, % operations. Add a text field to display the result. */

import java. awt. event. *; import java. applet. Applet; import java. awt. *; /*<applet code=Calc Width=300 Height=300 ></applet > */ public class Calc extends Applet implements Action. Listener { Text. Field t; String a; int p=0, tmp=0; Button b 0, b 1, b 2, b 3, b 4, b 5, b 6, b 7, b 8, b 9; Button badd, bsub, bmul, bdiv, bper, beql, bc; public void init(){ t = new Text. Field(50); b 0 = new Button("0"); b 1 = new Button("1"); b 2 = new Button("2"); b 3 = new Button("3"); b 4 = new Button("4"); b 5 = new Button("5"); b 6 = new Button("6"); b 7 = new Button("7"); b 8 = new Button("8"); b 9 = new Button("9"); badd = new Button("+"); bsub = new Button("-"); bmul = new Button("*"); bdiv = new Button("/"); bper = new Button("%"); bc = new Button("c"); beql = new Button("="); add(t); add(b 0); add(b 1); add(b 2); add(b 3); add(b 4); add(b 5); add(b 6); add(b 7); b 0. add. Action. Listener(this); b 1. add. Action. Listener(this); b 2. add. Action. Listener(this); b 3. add. Action. Listener(this); b 4. add. Action. Listener(this); b 5. add. Action. Listener(this); b 6. add. Action. Listener(this); b 7. add. Action. Listener(this); b 8. add. Action. Listener(this); b 9. add. Action. Listener(this); badd. Action. Listener(this); bsub. add. Action. Listener(this); bmul. add. Action. Listener(this); bdiv. add. Action. Listener(this); bper. add. Action. Listener(this); bc. add. Action. Listener(this); beql. add. Action. Listener(this); set. Layout(new Grid. Layout(4, 4)); }

public void action. Performed(Action. Event ae) { if(ae. get. Source()==bc) { if(ae. get. Source()==b 3){ t. set. Text("0"); } if(ae. get. Source()==b 0) { int k=Integer. parse. Int(t. get. Text()); k=k*10+0; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 1) { int k=Integer. parse. Int(t. get. Text()); k=k*10+1; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 2) { int k=Integer. parse. Int(t. get. Text()); k=k*10+2; t. set. Text(String. value. Of(k)); } int k=Integer. parse. Int(t. get. Text()); k=k*10+3; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 4) { int k=Integer. parse. Int(t. get. Text()); k=k*10+4; t. set. Text(String. value. Of(k)); }

if(ae. get. Source()==b 5) { int k=Integer. parse. Int(t. get. Text()); k=k*10+5; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 6) { int k=Integer. parse. Int(t. get. Text()); k=k*10+6; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 7) { int k=Integer. parse. Int(t. get. Text()); k=k*10+7; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 8) { int k=Integer. parse. Int(t. get. Text()); k=k*10+8; t. set. Text(String. value. Of(k)); } if(ae. get. Source()==b 9) { int k=Integer. parse. Int(t. get. Text()); k=k*10+9; t. set. Text(String. value. Of(k)); }

if(ae. get. Source()==badd) { tmp=Integer. parse. Int(t. get. Text()); p=1; t. set. Text("0"); } if(ae. get. Source()==bsub) { tmp=Integer. parse. Int(t. get. Text()); p=2; t. set. Text("0"); } if(ae. get. Source()==bmul) { tmp=Integer. parse. Int(t. get. Text()); p=3; t. set. Text("0"); } if(ae. get. Source()==bdiv) { tmp=Integer. parse. Int(t. get. Text()); if(ae. get. Source()==bper) { tmp=Integer. parse. Int(t. get. Text()); p=5; t. set. Text("0"); } if(ae. get. Source()==beql) { float ewval=Integer. parse. Int(t. get. Text()); float res=0;

switch(p) { case 1: res=tmp+newval; break; case 2: res=tmp-newval; break; case 3: res=tmp*newval; break; case 4: res=tmp/newval; break; case 5: res=tmp%newval; break; } t. set. Text(String. value. Of(res)); } } }

/*Week 6 : b) Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked. */

import java. applet. *; import java. awt. event. *; /*<applet code=Fact. Compute width=300 height=300> </applet>*/ public class Fact. Compute extends Applet set. Layout(new Grid. Layout(3, 2)); add(lbl 1); add(tf 1); add(lbl 2); add(tf 2); implements Action. Listener{ Button btn, clearbtn; Label lbl 1, lbl 2; Text. Field tf 1, tf 2; public void init() { btn=new Button("COMPUTE"); btn. add. Action. Listener(this); clearbtn=new Button("CLEAR"); clearbtn. add. Action. Listener(this); tf 1=new Text. Field(30); tf 2=new Text. Field(30); lbl 1=new Label("NUMBER"); lbl 2=new Label("RESULT"); add(btn); add(clearbtn); }

public void action. Performed(Action. Event e) { if(e. get. Source()==btn) { int a=Integer. parse. Int(tf 1. get. Text()); int fact=1; for(int i=1; i<=a; i++) fact*=i; tf 2. set. Text(""+fact); } else { tf 1. set. Text(""); tf 2. set. Text(""); } } }

// Demonstrate Flow. Layout using applets import java. awt. *; import java. awt. event. *; import java. applet. *; /* <applet code="Flow. Layout. Demo 2" width=250 height=150> </applet> */ public class Flow. Layout. Demo 2 extends Applet implements Action. Listener { String msg = ""; Button yes, no, maybe; public void init() { set. Layout(new Flow. Layout()); yes = new Button("Yes"); no = new Button("No"); maybe = new Button("Undecided"); add(yes); add(no); add(maybe); yes. add. Action. Listener(this); no. add. Action. Listener(this); maybe. add. Action. Listener(this); }

public void action. Performed(Action. Event ae) { String str = ae. get. Action. Command(); if(str. equals("Yes")) { msg = "You pressed Yes. "; } else if(str. equals("No")) { msg = "You pressed No. "; } else { msg = "You pressed Undecided. "; } repaint(); } public void paint(Graphics g) { g. draw. String(msg, 6, 100); } }
- Slides: 45