
Understanding Java Applets in Web Development
"Learn about the difference between local and remote applets, how they work, and their integration in web pages. Explore the features and security considerations of Java applets for enhanced user experiences."
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Local applet A local applet is one that is stored on your own computer system. When your Web page must find a local applet, it doesn't need to retrieve information from the Internet-in fact, your browser doesn't even need to be connected to the Internet at that time
<applet codebase="tictactoe" code="TicTacToe.class" width=120 height=120> </applet>
Remote Applet A remote applet is one that is located on another computer system. This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter where the remote applet is located, it's downloaded onto your computer via the Internet. Your browser must, of course, be connected to the Internet at the time it needs to display the remote applet.
<applet codebase="http://www.myconnect.com/applets/" code="TicTacToe.class" width=120 height=120> </applet>
Differ from Application An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal. There are some important differences between an applet and a standalone Java application, including the following An applet is a Java class that extends the java.applet.Applet class. A main() method is not invoked on an applet, and an applet class will not define main(). Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment. The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime. Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed. Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Preparing to Write Applets Until now we have been creating simple Java application program with a single main() method that created objects, set instance variables and ran methods. To write any applet, we will need to know: When to use applets. How an applet works, What sort of features an applet has, and Where to start, when we first create our own applet. The following are the steps that are involved in developing and testing and applet. 1.Buliding an applet code(.java file) 2.Creating an executable applet(.class file) 3.Designing a web page using HTML 4.Preparing <Applet Tag> 5.Incorporating <Applet> tag into the web page. 6.Creating HTML file 7.Testing the applet code. .
Building Applet Code Importing the Applet class Here is the directive that you need: import java.applet.Applet; import is a keyword java. applet is the name of the package A dot ( . ) separates the package from the class Applet is the name of the class. There is a semicolon ( ; ) at the end
To building the applet code two classes of java library are essential namely Applet and Graphics. The Applet class is contained in java.applet package provides life and beehaviour to the applet through its methods such as int(), start() and paint(). Unlike with applications, where java calls the main() method directly to initiate the execution of the program, when an applet is loaded java automatically calls a series of Applet class methods for starting running and stopping the applet code. The Applet class therefore maintains the life cycle of an applet. To display the result of the applet code, the paint() method of the Applet class is called up. The output may be test, graphics, or sound. The syntax of paint() method which requires a Graphic object as an argument, is defined as follows: public void paint(Graphics g) This requires that the applet code imports the java.awt package that contain the Graphic class. All output operations of an applet are performed using the methods defined in the graphics class.
The general format of applet code is as following import java.awt.*; import java.applet.*; ___________________ ___________________ public class applet classnameextends Applet { ................................. ................................statements ................................ ................................ public void paint(Graphics g) { .......................... ..........................//Applet operations code ......................... } ...................... ..................... }
Creating an Executable Applet Executable applet is nothing but the .class file of applet, which is obtained by compiling the source code of the applet. Compiling the applet is exactly the same as compiling an application using following command. javac appletname.java The compiled output file called appletname.classshould be placed in the same directory as the source file.
Designing a Web Page Java appleta are programs that reside on web page. A web page is basically made up of text and HTML tags that can be interpreted by a web browser or an applet viewer. Like Java source code, it can be prepared using any ASCII text editor. A web page is also called HTML page or HTML document. Web pages are stored using a file extension .html such as my Applet.html. Such files are referred to as HTML files. HTML files should be stored in the same directory as the compiled code of the applets. A web page is marked by an opening HTML tag <HTML> and closing HTML tag </HTML> and is divided into the following three major parts: 1) Comment Section 2) Head Section 3) Body Section
Comment Section This is very first section of any web page containing the comments about the web page functionality. It is important to include comments that tell us what is going on in the web page. A comment line begins with <! And ends with a > and the web browsers will ignore the tesxt enclosed between them. The comments are optional and can be included anywhere in the web page. Head Section This section contains title, heading and sub heading of the web page. The head section is defined with a starting <Head> tag and closing </Head> tag. <Head> <Title> Welcome to Java Applet </Title> </Head>
Body Section After the Head Section the body section comes. This is called as body section because the entire information and behaviourof the web page is contained in it, It defines what the data placed and where on to the screen. It describes the color, location, sound etc. of the data or information that is going to be placed in the web page. <Body> <Center> <H1> Welcome to Java > </H1> </Center> <BR> <APPLET - - -> </APPLET> </Body>
Applet Tag The <Applet...< tag supplies the name of the applet to be loaded and tells the browser how much space the applet requires. The ellipsis in the tag <Applet...> indicates that it contains certain attributes that must specified. The <Applet> tag given below specifies the minimum requirements to place the Hellojava applet on a web page. <Applet code = Hellojava.class width = 400 Height = 200 > </Applet>
This HTML code tells the browser to load the compiled java applet Hellojava.class, which is in the same directory as this HTML file. It also specifies the display area for the applet output as 400 pixels width and 200 pixels height. We can make this display area appear in the center of screen by using the CENTER tags as showsn below: <CENTER> <Applet> ------------- ------------- ------------- </Applet> </CENTER> The applet tag discussed above specified the three things: 1) Name of the applet 2) Width of the applet (in pixels) 3) Height of the applet (in pixels)
Adding Applet to HTML File To execute an applet in a web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes SimpleApplet: <Applet code = Hellojava.class width = 400 Height = 200 > </Applet> The width and height attributes specify the dimensions of the display area used by the applet. After you create this file, you can execute the HTML file called RunApp.html (say) on the command line. c:\>appletviewer RunApp.html
Running the Applet To execute an applet with an applet viewer, you may also execute the HTML file in which it is enclosed, eg. c:\>appletviewer RunApp.html Execute the applet the applet viewer, specifying the name of your applet's source file. The applet viewer will encounter the applet tagewithin the comment and execute your applet.
First Java Applet Program import java.awt.*; import java.applet.*; public class FirstJavaAppletextends Applet { public void paint(Graphics g) { g.drawString("My First Java Applet Program",100,100); } }
<HTML> <HEAD> <TITLE>My First Java Applet Program</TITLE> </HEAD> <BODY> <APPLET Code="FirstJavaApplet.class" Width=300 Height=200> </APPLET> </BODY> </HTML>
Applet Life Cycle An applet is a window based event driven program and it waits until an event occurs. The AWT notifies the applet about an event by calling an event handler that has been provided by applet. Applet should not enter a "mode" of operation in which it maintains control for an extended period. In these situations you must start an additional thread of execution. The user initiates interaction with an applet. For example, when the user clicks a mouse inside the applet's window, a mouse-clicked event is generated. Applets can contain many controls such as push button check boxes. When the user interacts with one of these controls, an event is generated.
public class AppProgram extends Applet { public void init() { //initializtion } public void start() { //start or resume execution } public void stop() { //suspend execution } public void destroy() { //perform shutdown activities } public void paint(Graphics g) { //redisplay contents of window } } The skeleton generates the blank applet window when viewed with an applet viewer. This skeleton does not do anything.
Initialization State When the browser downloads an HTML page containing applets, it creates an instance for each of the Applet classes, using the no arg constructor. Applet must have a no argument constructor otherwise it cannot be loaded. Initialization can be done through init(). The init() method is the first method to be called. It is used to initialize the applet each time it is reloaded. Applets can be used for setting up an initial state, loading images or fonts, or setting parameters. For example: public void init() { //code here }
Running State Immediately after calling init(), the browser calls the start() method. start() is also called when user returns to an HTML page that contains the applet. So, it ht user leaves a web page and come back, the applet resumes execution at start(). So, when the applet called the start() Method it is called its running state. Staring can also occur if the applet is already in "stopped" (idle) state. public void start() { ____________________ ____________________ (Action) ____________________ }
Idle or Stopped State When we leave the page containing the currently running applet, then it stop running and becomes idle. We can also do so by calling stop() Method explicitly. public void stop() { ____________________ ____________________ (Action) ____________________ }
Dead State When an applet is completely removed from the Memory, it is called dead. This occurs automatically by invoking the destroy() method when we quit the browser Like initialization, dead state occurs only once in the applet's life cycle. public void destroy() { ____________________ ____________________ (Action) ____________________ }
Display State Painting is how an applet displays something on screen-be it text, a line, a colored background, or an image. The paint() method is used for displaying anything on the applet paint() method takes an argument, an instance of class graphics. The code given can be as follows: public void paint(Graphics g) { } where Graphics class contains the member functions that can be used to display the output to the browser. text String, the drawString() method is used. g.drawString(String s, int x, int y) where x and y are the coordinate positions on the screen and s is the string to be output.
Parameter passing to Applet or PARAM tag Java allows users to pass user-defined parameters to an applet with the help of <PARAM>tags. The <PARAM>tag has a NAME attribute which defines the name of the parameter and a VALUE attribute which specifies the value of the parameter. In the applet source code, the applet can refer to the parameter by its NAME to find its value. The syntax of the <PARAM>tag is: <APPLET> <PARAMNAME=parameter1_name VALUE=parameter1_value> <PARAMNAME=parameter2_name VALUE=parameter2_value> <PARAMNAME=parametern_nameVALUE=parametern_value> </APPLET>
For example, consider the following statements to set the text attribute of applet to This is an example of Parameter <APPLET> <PARAMNAME=text VALUE=This is an example of Parameter!!!> </APPLET> Note that the <PARAM>tags must be included between the <APPLET> and</ APPLET> tags. The init () method in the applet retrieves user-defined values of the parameters defined in the <PARAM>tags by using the get Parameter () method. This method accepts one string argument that holds the name of the parameter and returns a string which contains the value of that parameter. Since it returns String object, any data type other than String must be converted into its corresponding data type before it can be used.
To retrieve a parameter's value, we need to use getParameter() method of Applet class. public String getParameter(String name) Method takes a String argument name, which represents the name of the parameter which was specified with the param attribute in the <applet> tag. Method returns the value of the name parameter(if it was defined) else null is returned.
Setting Color The Color class provides various methods to use any color you want in display. It defines various color constants which can be directly used only by specifying the color of your choice. In addition, the Color class allows creation of millions of colors. The Color class contains three primitive colors namely, red, blue and green and all other colors are a combination of these three colors. One of the constructors that is used to create color of your choice is Color (intred, intgreen, int blue) where, red, green, blue can take any value between 0 and 255.
Setting Background To set the color of the background of an applet window, setBackground () method is used. The general form of the setBackground () method is voidsetBackground(mycolor)
Setting Foreground Color The general form of the setForeground () method is void setForeground(mycolor) where, mycolor is one of the color constants or the new color created by the user
The list of color constants is given below: Color.red Color.orange Color.gray Color.darkGray Color.lightGray Color.cyan Color.pink Color.white Color.blue Color.green Color.black Color.yellow
import java.awt.*; import java.applet.*; /* <applet code="appletColor" width="400" height="200"> </applet> */ public class appletColorextends Applet { public void init() { setForeground(Color.white); setBackground(Color.blue); } public void paint(Graphics g) { g.drawString("ProgrammingUnit", 10, 100); } }
Update()Method The repaint () method causes then AWT runtime system to execute the update () method of the Component class which clears the window with the background color of the applet and then calls the paint () method. But sometimes erasing the background is undesirable. For example: If user wants to display the x and y coordinates of each location where the mouse is clicked instead of only the currently clicked location then it is not possible using the default version of the update () method. Each time the user clicks in the applets's window, the coordinates of the previously clicked location are erased and only the coordinates of the currently clicked location are displayed. To overcome this problem, it is necessary to override the update () method to invoke paint () directly, thus avoiding the erasure of the component's background.
public void update() { //redraw a window } public void paint(Graphics g) { update(); }
Repaint () Method The paint () method is called automatically by the environment (usually a web browser) that contains the applet whenever the applet window needs to be redrawn. This happens when the component is first displayed, but it can happen again if the user minimizes the window that displays the component and then restores it or if the user moves another window over it and then move that window out of the way. In addition to these implicit calls to the paint() method by the environment, one can also call the paint () method explicitly whenever the applet window needs to be redrawn, using the repaint () method. The repaint () method causes the AWT runtime system to execute the update () method of the Component class which clears the window with the background color of the applet and then calls the paint () method.
void repaint ( ) This causes the entire window to be repainted. Other versions that will cause repaint are: void repaint(intleft, int top, intwidth, int height) If your system is slow or busy, update( ) might not be called immediately. If multiple calls have been made to AWT within a short period of time, then update( ) is not called very frequently. This can be a problem in many situations in which a consistent update time is necessary. One solution to this problem is to use the following forms of repaint( ): void repaint (long maxDelay) void repaint (long maxDelay, intx, inty, intwidth, int height) Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called. If the time elapses before update( ) can be called, it isn't called. It is possible for a method other than paint( ) or update( ) to output to an applet's window. To do so, it must obtain a graphics context by calling getGraphics( ) and then use this context to output to the window. For most applications, it is better and easier to route window output through paint( ) and to call repaint( ) when the contents of the window change .
C:\>javac ControlLoopApplet.java C:\>appletviewer ControlLoopApplet.java
Font The Font class provides a method of specifying and using fonts. The Font class constructor constructs font objects using the font's name, style (PLAIN, BOLD, ITALIC, or BOLD+ITALIC), and point size. Java's fonts are named in a platform independent manner and then mapped to local fonts that are supported by the operating System on which it executes. The getName() method returns the logical Java font name of a particular font. The getFamily() method returns the operating system-specific name of the font. The standard Java font names are Courier, Helvetica, TimesRoman etc. The font can be set for a graphics context and for a component. Font getFont() It is a method of Graphics class used to get the font property. setFont(Font f) is used to set a font in the graphics context.