Download presentation
Presentation is loading. Please wait.
1
APPLETS
2
What are the differences between Applets and Application?
What is Applets? An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). What are the differences between Applets and Application? Applets do not use the main() method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code. Unlike stand – alone applications, applets cannot be run independently. They are run from inside a Web page using a special feature known as HTML tag. Applets cannot read from or write to the files in the local computer. Applets cannot communicate with other servers on the network. Applets cannot run any program from the local computer. Applets are restricted from using libraries from other languages such as C or C++. (Java language supports this feature through native methods.)
3
Applet Architecture An applet is a window – based program.
First, applets are event driven. Event – driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler appropriate action and then quickly return control to the AWT. Second, the user initiates interaction with an applet - not the other way around. As you know, in a non - windowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine(). This not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when must respond. For example, when the user clicks a mouse inside the applet’s window, a mouse – clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. Applets can contain various controls, such as push buttons and check boxes.
4
Applet Architecture 12. When the user interacts with one of these controls, an event is generated. 13. While the architecture of an applet is not as easy to understand as that of a console – based program, Java’s AWT makes it as simple as possible. 14. If you have written programs for windows, you know how intimidating that environment can be. 15. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.
5
An Applet Skeleton or Applet Life Cycle
Born Begin (Load Applet) Initialization start( ) Running stop( ) Idle Stopped start( ) Display paint( ) destroy( ) Dead End Destroyed Exit of Browser
6
An Applet Skeleton or Applet Life Cycle
All but the the most trivial applets override 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, paint(), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do no need to override those methods they do not use. However, only very simple applets will not need to define all of them. The applet states is: 1. Born or initialization state 2. Running state 3. Idle state 4. Dead or destroyed state 5. Display state
7
Initialization State Applet enters the initialisation state when it is first loaded. This is achieved by calling the init() method of Applet Class. The applet is born. At this stage, we may do the following, if required, a. Create objects needed by the applet. b. Set up initial values c. Load images or fonts d. set up colors public void init( ) { } Action
8
2. Running State Applets enters the running state when the system call the start () method of Applet Class. This occurs automatically after the applet is initailized. Starting can also occur if the applet is already in “stopped” state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that, unlike init() method, the start() method may be called more than once. We may override the start() method to create a threa to control the applet. public void start( ) { } Action
9
3. Idle or Stopped State An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate the thread. We can achieve by overriding the stop( ) method: public void stop( ) { } Action
10
4. Dead State An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources. Like threads we may override the destroy( ) method to clean up these resouces. public void destroy( ) { } Action
11
5. Display State Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method. Like other methods in the life cycle, the default version of paint() method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint (Graphics g) { } Display Statements
12
Specified Colors Specified Colors Color.black 10. Color.pink
import java.awt.*; import java.applet.*; /* <applet code = "AppletDemo" width = 300 height = 300> </applet> */ public class AppletDemo extends Applet { String msg; public void init() setBackground(Color.cyan); setBackground(Color.red); setForeground(Color.blue); } public void start() msg = "This is Start method"; public void stop() msg = "This is Stop method"; public void destroy() msg = "This is Destroy method"; public void paint(Graphics g) g.drawString(msg,100,100); Specified Colors Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Specified Colors 10. Color.pink 11. Color.red 12. Color.white 13. Color.yellow
13
How the applets to be displayed in the Browser
<HTML> <HEAD> <TITLE>WELCOME TO cHETTINAD</TITLE> </HEAD> <BODY> <APPLET CODE = AppletDemo.class WIDTH = 300 HEIGHT = 200 </APPLET> </BODY> </HTML>
14
The HTML APPLET Tag < APPLET [CODEBASE = codebaseURL]
CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [<PARAM NAME = AttributeName VALUE = AttributeValue>] [HTML Displayed in the absence of Java] </APPLET>
15
ATTRIBUTE MEANING CODE = AppletFileName.class
Specifies the name of the applet class to be loaded. That is, the name of the already – compiled .class file in which the executable. Java bytecode for the applet is stored. This attribute must be specified. CODEBASE = codebase_URL (Optional) Specifies the URL of the directory in which the applet resides. If the applet resides in the same directory as the HTML file, then the CODEBASE attirbute may be omitted entirely. WIDTH = pixels HEIGHT = pixels These attributes specify the width and height of the space on the HTML page that will be reserved for the applet. NAME=applet_instance_name A name for the applet may optionally be specified so that other applets on the page may refer to this applet. This facilitates inter applet communication. ALIGN = alignment This optional attribute specifies where on the page the applet will appear. Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE. HSPACE = pixels Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies the amount of horizontal blank space the browser should leave surrounding the applet. VSPACE = pixels Used only when some vertical alignment is specified with the ALIGN attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical blank space the browser should leave surrounding the applet. ALT = alternate_text Non – java browser will display this text where the applet would normally go. This attribute is optional. PARAM NAME AND VALUE The PARAM tag allows you to specify applet – specific arguments in an HTML page. Applets access their attributes with the getParameter() method
16
Passing Parameters to Applets
import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width = 300 height = 300> <param name = fontName value=Courier> <param name = fontSize value = 30> <param name = leading value=2> <param name = accountEnabled value = true> </applet> */ public class ParamDemo extends Applet { String fontName; int fontSize; float leading; boolean active; public void start() String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found";
17
param = getParameter("fontSize");
try { if(param != null) //if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) fontSize = -1; param = getParameter("leading"); if(param != null) //if not found leading = Float.valueOf(param).floatValue(); leading = 0; leading = -1;
18
param = getParameter("accountEnabled");
if(param != null) active = Boolean.valueOf(param).booleanValue(); } public void paint(Graphics g) { g.drawString("Font name: " + fontName,0,10); g.drawString("Font Size: " + fontSize,0,20); g.drawString("Leading: " + leading, 0,42); g.drawString("Account Active: " + active,0,58);
19
getCodeBase() and getDocumentBase()
import java.awt.*; import java.applet.*; import java.net.*; /* <applet code=ParamDemo_2.class width = 300 height = 300> </applet> */ public class ParamDemo_2 extends Applet { public void paint(Graphics g) String msg; URL url = getCodeBase(); msg = "Code Base: " + url.toString(); g.drawString(msg,10,20); url = getDocumentBase(); msg = "Document Base: " + url.toString(); g.drawString(msg,10,40); }
20
The AudioClip Interface
The AudioClip interface defines these methods: 1. play ( ) – play a clip from the beginning. 2. stop ( ) – stop playing the clip. 3. loop ( ) – play the loop continuously. 4. getAudioClip ( ) - After you have loaded an audio clip import java.applet.*; import java.awt.event.*; import java.awt.*; /* <applet code=SoundExample width = 300 height = 300> </applet> */ public class SoundExample extends Applet implements MouseListener { AudioClip soundFile1; AudioClip soundFile2;
21
addMouseListener(this); setBackground(Color.yellow);
public void init() { soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav"); soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav"); addMouseListener(this); setBackground(Color.yellow); soundFile1.play(); } public void paint(Graphics g) g.drawString("Click to hear a sound",20,20); public void mouseClicked(MouseEvent evt) soundFile2.play(); public void mousePressed(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {}
22
AppletStub Interface The AppletStub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. Methods public abstract boolean isActive () The isActive() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to isActive() return false. The system marks the applet active just prior to calling start(); after this point, calls to isActive() return true. public abstract URL getDocumentBase () The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the getImage() or getAudioClip() methods to load an image or audio file relative to the HTML file. public abstract URL getCodeBase () The getCodeBase() method returns the complete URL of the .class file that contains the applet. This method can be used with the getImage() method or the getAudioClip() method to load an image or audio file relative to the .class file.
23
public abstract String getParameter (String name)
The getParameter() method allows you to get parameters from <PARAM> tags within the <APPLET> tag of the HTML file that loaded the applet. The name parameter of getParameter() must match the name string of the <PARAM> tag; name is case insensitive. The return value of getParameter() is the value associated with name; it is always a String regardless of the type of data in the tag. If name is not found within the <PARAM> tags of the <APPLET>, getParameter() returns null. public abstract void appletResize (int width, int height) The appletResize() method is called by the resize method of the Applet class. The method changes the size of the applet space to width x height. The browser must support changing the applet space; if it doesn't, the size remains unchanged.
24
import java.awt.*; import java.applet.*; /* <applet code=Control.class height=300 width=300> </applet> */ public class Control extends Applet { public void init() Button b = new Button("Click Here"); Checkbox cb = new Checkbox("Chettinad"); Choice os = new Choice(); os.add("Windows 98"); os.add("Windows XP"); os.add("Windows 2000"); os.add("Windows vista");
25
List ls = new List(); ls.add("Chettinad"); ls.add("College"); ls.add("Engineering"); ls.add("Technology"); Label lb = new Label("Enter the A Value"); TextField tf = new TextField(12); String val = “dfasdfsdafasddfsdafsafsdasjlsdjgkl;sdjklgjljglsdjglsj"; TextArea ta = new TextArea(val,10,30); add(b); add(cb); add(os); add(ls); add(lb); add(tf); add(ta); } }
26
import java.awt.*; import java.applet.*; /* <applet code=TextDemo.class height=300 width=300> </applet> */ public class TextDemo extends Applet { TextField text1,text2; public void init() text1 = new TextField(8); text2 = new TextField(8); add(text1); add(text2); text1.setText("123"); text2.setText("215"); }
27
public void paint(Graphics g)
{ int x = 0,y = 0,z = 0; String s1,s2,s; g.drawString("Enter the Number into Each Text Field", 10,50); try s1 = text1.getText(); x = Integer.parseInt(s1); s2 = text2.getText(); y = Integer.parseInt(s2); } catch(Exception ex) { } z = x + y; s = String.valueOf(z); g.drawString("The sum is: ",10,75); g.drawString(s,100,75);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.