53511525-40546729-Java - java.applet package examples -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: java.applet package examples - Applet Tutorials 1. What is Applet This section introduces you with the applet and describes the advantages and disadvantages of applet. 2. Applet versus Application This section defines the various differences between the Applets and the Applications. 3. Understanding Applet Life Cycle In this section you will learn about the lifecycle of an applet. You will learn about the different methods of an applet. 4. HTML for Java Programmers o Welcome to the Internet Now a days Java has become so stupendous that we can't even think of WWW(World Wide Web) without it. As we all know that WWW is a collection of computing and information resources. o What Exactly is HTML? Now lets see what exactly is HTML (Hyper Text Markup Language). It is a type of data file which is transferred to the client machine. The HTML file gets translated and displayed on the screen if the client is using a Web browser like Netscape Navigator, Microsoft Internet Explorer etc. o Java and HTML: The Basics Before going any further lets start with the basics of HTML first. In this section we will come to know about all the tags which are required for the applet to be displayed within the browser. o The <APPLET> Tag in Detail After understanding a simple Java-enabled Web page lets explore the APPLET tag now. o <APPLET> Tag Parameters: The <PARAM> Tag These are the parameters passed directly to a Java applet. Parameters are to applets what command-line arguments are to applications. These parameters allow the user to customize the applet's operation. APPLET parameters stored in the PARAM tag actually have little directly to do with HTML. o HTML Document Creation We have already come to know about the Java Applets to be embedded within the HTML pages. There are several tags used in HTML however in this section we will provide an introduction to HTML for Java programmers. 5. Creating First Applet In this section you will create our first applet example and then run in the browser. 6. Drawing Shapes This section shows you how to draw circle and lines in applet. 7. Drawing Shapes using color Applet allows you to play with colors. In this section you will learn how to draw different shapes using colors of your choice. 8. Event Listeners This section shows you how to write applications that responds to the user actions. 9. Passing Parameters To Applet In this example you will learn how to pass parameters from html page to an applet. You can then use these parameters values for further processing or for some business processing. 10. Opening a URL from an Applet From the applet it is possible to open another url (web page). In this example you will learn how to accomplish it. 11. Opening new browser window from an Applet This section shows you how to open new browser window from Applet. 12. Applet not working error This section describes you some of the trouble shooting when your applet is not working in the browser. 13. Applet Read File Example This section shows how to write program to read disc file from an applet. 14. Applet Write Files Example This section shows you how to write to a file from an applet. 15. Display image in the applet In this section you will learn how to display image on you applet. 16. Play sound in applet In this section you will learn how to play sound using your applet. 17. Applet Servlet example In this example you will learn how to communicate to your servlet through applet. 18. Applet Security - Understanding applet security In this section you will learn about security issues with the applet. You will learn about securing the applet. 19. Java Applet Signing Example This section explains you how you can sign your applet for security reasons. 20. Swing applet Example This example shows you how to use swing components with you applet. 21. Applet Banner Here, we will learn about making the banner in java applet. Simply the banner is used to advertising for any institution, shops and any organizations. The advertising can be done by the different - different ways but the main aim is to popular our organization. 22. Clock Applet Here is a sample of running clock provided by the java applet to illustrate how to use the clock in an applet. This program shows the current time. This type of program is used to display the time on browser where your application is running on. 23. Java - Opening a url in new window from an applet This is the example of opening a url from an applet. This program shows that how a url is opened in a new document or browser. When you click the button "google", new browser window will open displaying the specified url, in our case url is http://www.google.com. 24. Java - Opening a URL from an Applet This is the example of opening a url in same window from an applet. This program shows that how a url is opened in same document or browser window. What is an Applet - Java Applet Tutorial Introduction Applet is java program that can be embedded into HTML pages. Java appletsruns on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining. Advantages of Applet: y y y y y y Applets are cross platform and can run on Windows, Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox, so the user does not need to trust the code, so it can work withoutsecurity approval Applets are supported by most web browsers Applets are cached in most web browsers, so will be quick to load when returning to a web page User can also have full access to the machine if user allows Disadvantages of Java Applet: y y y y Java plug-in is required to run applet Java applet requires JVM so first time it takes significant startup time If applet is not already cached in the machine, it will be downloaded from internet and will take time Its difficult to desing and build good user interface in applets compared to HTML technology Applet versus Application Applets as previously described, are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method. Applets can run in our browser's window or in an appletviewer. To run the applet in an appletviewer will be an advantage for debugging. Applets are designed for the client site programming purpose while the applications don't have such type of criteria. Applet are the powerful tools because it covers half of the java language picture. Java applets are the best way of creating the programs in java. There are a less number of java programmers that have the hands on experience on java applications. This is not the deficiency of java applications but the global utilization of internet. It doesn't mean that the java applications don't have the place. Both (Applets and the java applications) have the same importance at their own places. Applications are also the platform independent as well as byte oriented just like the applets. Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applications are designed to exists in a secure area. while the applets are typically used. Applications and applets have much of the similarity such as both have most of the same features and share the same resources. Applets are created by extending the java.applet.Applet class while the java applications start execution from the main method. Applications are not too small to embed into a html page so that the user can view the application in your browser. On the other hand applet have the accessibility criteria of the resources. The key feature is that while they have so many differences but both can perform the same purpose. Review of Java Applets: You have previously learned about the java applets. To create an applet just create a class that extends the java.applet.Applet class and inherit all the features available in the parent class. The following programs make all the things clear. import java.awt.*; import java.applet.*; class Myclass extends Applet { public void init() { /* All the variables, methods and images initialize here will be called only once because this method is called only once when the applet is first initializes */ } public void start() { /* The components needed to be initialize more than once in your applet are written here or if the reader switches back and forth in the applets. This method can be called more than once.*/ } public void stop() { /* This method is the counterpart to start(). The code, used to stop the execution is written here*/ } public void destroy() { /* This method contains the code that result in to release the resources to the applet before it is finished. This method is called only once. */ } public void paint(Graphics g) { /* Write the code in this method to draw, write, or color things on the applet pane are */ } } In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the requirements. The major difference between the two (applet and application) is that java applications are designed to work under the homogenous and more secure areas. On contrary to that, java applets are designed to run the heterogeneous and probably unsecured environment. Internet has imposed several restrictions on it. Applets are not capable of reading and writing the user's file system. This means that the applet neither can access nor place anything locally. To illustrate this lets take an example.. Many Window based C applications uses the .INF file as the initialization file to store the information about the application and any user preferences in 16-bit Windows or the Registry in 32-bit Windows. While in case of current applet it is not possible. One more thing to point here is that applets are unable to use the native methods, run any program on the user system or load shared libraries. The major security concern here is that the local shared libraries and the native methods may results in the loophole in the java securitymodel. Applets are not capable of communicating the server than one from which they are originating. There are the cases in which an encryption key is used for the verification purpose for a particular applet to a server. But accessing a remote server is not possible. The conclusion is that the java applets provides a wide variety of formats for program execution and a very tight security model on the open environment as on the Internet. Introduction to Java Application : Java applications have the majority of differences with thejava applets. If we talk at the source code level, then we don't extend any class of the standard java library that means we are not restricted to use the already defined method or to override them for the execution of the program. Instead we make set of classes that contains the various parts of the program and attach the main method with these classes for the execution of the code written in these classes. The following program illustrate the structure of the java application. public class MyClass { /* Various methods and variable used by the class MyClass are written here */ class myClass { /* This contains the body of the class myClass */ } public static void main(String args) { /* The application starts it's actual execution from this place. **/ } } The main method here is nothing but the system method used to invoke the application. The code that results an action should locate in the main method. Therefore this method is more than the other method in any java application. If we don't specify the main method in our application, then on running the application will through an exception like this one: In the class MyClass: void main(String args) is undefined But at higher level major concern is that in a typical java application security model, an application can access the user's file system and can use native methods. On properly configuring the user's environment and the java application it will allow access to all kind of stuff from the Internet. In most of the cases it is seen that the java application seems like a typical C/C++ application. Now we are going to create plenty of applications to exemplify some of the methods and features of a specific Java application. All of them are console based Java applications because here we are not going to cover the AWT. Java Applications : An Example Lets create an application that executes at the command prompt. Lets create a new file named ClassA.java. public class ClassA{ //write the variables for Class String Name; int AccNumber; float Bal; //This method display the information on the screen. void display(){ System.out.println("Name: " + Name); System.out.println("Account Number: " + AccNumber); System.out.println("Balance: " + Bal); } public static void main(String args) { //Create an instance of ClassA ClassA a = new ClassA(); //Assigning values to the variables in class ClassA a.Name = "Vinod"; a.AccNumber = 467256282; a.Bal =635; //Draw the top border for (int i = 0; i < 20; i++) System.out.print("--"); //Title System.out.println(" PARTICULARS"); //Call method to display the information a.display(); //Draw bottom border for (int i = 0; i < 20; i++) System.out.print("--"); //Ending remark System.out.println("End of display"); } } If the file ClassA.java and the javac.exe are in the same directory then compile the program just by giving the following command. javac ClassA.java If the file ClassA.java and javac.exe are not in same directory the set the path of java \bin directory in the environment variable and include the directory contained the file ClassA.java in the command prompt then apply the above command. After compiling the program, just apply the following command. java ClassA This will result in the following output. ---------------------------------------- PARTICULARS Name: Vinod Account Number: 467256282 Balance: 635.0 ----------------------------------------End of display The above example ClassA.java uses the three variables Name, AccNumber, and Bal and a display method to display the values of the variables. Everything is all right in the above example. Here is a closer look about the line System.out.println(). System is a class which is kept in java.lang package, out is an object of System class that is used to print the message on the standard output and println() is the method of the System class. Note the points given below: y y y The file ClassA.java makes the .class file after compilation. There is no need of specifying the extension when interpreting the file. While distributing the file just provide the compiled file (.class file) and the interpreter. System class contains the following variables and methods. Variables of the System class Variables Utilization public static PrintStream in public static PrintStream out public static PrintStream err It is used to read the data from the standard input stream It is used to write the data on the standard output stream It is used to print the error message on the standard output stream. Methods defined in the System class Methods getProperties() getProperty (String key, String default) setProperties (Properties props) gc() exit(int status) currentTimeMillis() Utilization It returns a Properties class with the system properties. Returns a String with a value for the specified property. Or, returns the default if the specified property is not set. Sets the system properties based on the specified properties. Manually invokes the garbage collector. Note that unless garbage collection is manually enabled or disabled, it is done automatically by the Java virtual machine. Exits the application with the specified status code (0 if successful). Returns a long that holds the value in milliseconds since January 1, 1970. arraycopy (Object src, int src Position, Object dst, dstPosition, int len) Copies an array. runFinalization () Runs the finalization methods of any object pending finalization. Importing Other packages to your Java Application: Lets create a simple application that displays the date. In this application you will see how to import packages in your application. Java libraries provide a built in method currentTimeMillis(). This method returns the number of seconds since January 1970 representing in 64-bit integer long format. public class PrintDate { public static void main(String args) { //Draw the upper border for (int i = 0; i < 40; i++) System.out.print("--"); //Display the timeT System.out.println("Time in milliseconds since January 1, 1970: " + System.currentTimeMillis()); //Draw the lower border for (int i = 0; i < 40; i++) System.out.print("--"); } } Compile the above program by giving the following command. javac PrintDate.java By giving the following command you will see the following output. java PrintDate Here is the output of the above program: -------------------------------------------------------------------Time in milliseconds since January 1, 1970: 1181398838332 -------------------------------------------------------------------- To avoid the overflow and inaccuracy here we took integer data type as long. It is a 64-bit signed integer and will contain the values up to the year 200,000,000 accurately. So we should not worry right now because this problem will take a long time to occur. Now come to the point: Suppose the user wanted today's date in your application then no need to worry because java provides the built in class Date in the package java.util that provides this functionality. Since java.util is not a default package so we have to import it explicitly to use the functionality of the class Date. You will be known about the syntax of importing the package in your application. There is no difference of importing the package in both Java Application and the Java Applet. But don't worry i will provide you the code of importing the package in your application or applet. Here is the code of importing the package. import java.util.Date; Write this code in the beginning of your application, then your application can access to all the non-private member of Date class. Now I would like to give one more example of the java application that will have access the private members of the Date class. import java.util.Date; public class PrintDate2 { Date todayDate = new Date(); public static void main(String args){ //Draw the upper border for (int i = 0; i < 40; i++) System.out.print("--"); //Instantiate the class PrintDate2 PrintDate2 d = new PrintDate2(); //Display the Date System.out.println("Today's Date: " + d.todayDate); //Draw the lower border for (int i = 0; i < 40; i++) System.out.print("--"); } } Compile and run the above application. On running the above application displays the current date and also shows the upper and lower border. Here is the output of the above program: -----------------------------------------------------Today's Date: Sat Jun 09 16:31:51 BST 2007 ------------------------------------------------------ Using args to pass Command Line Arguments: Any application can have one more attribute that is they can receive the command line argument pass to it. Let us consider the case of an application named ClassA to which we have to pass the arguments while running the application then what have to be done. In this case we pass the argument by using the command line argument technique. public class CommandLine { public static void main(String args){ //Draw the upper border for (int i = 0; i < 40; i++) System.out.print("--"); //Check to see if no argument was passed if (args.length == 0){ System.out.println("Enter the argument "); } // Loop to display the argument passed to the command line for (int i = 0; i < args.length; i++) System.out.println(" " + args[i]); //Draw the bottom border for (int i = 0; i < 40; i++) System.out.print("--"); } } Here is the code used to pass the arguments by using the command line argument technique. java CommandLine This is my first program C:\Upload>java CommandLine This is my first program --------------------------------------------------------This is my first program --------------------------------------------------------- What happens when we pass the arguments within the double quotes. java CommandLine "This is my first program" C:\Upload>java CommandLine "This is my first program" ----------------------------------------------------------This is my first program ----------------------------------------------------------- So the conclusion is that if we pass the argument on the command line by using the first technique then the arguments are stored like this. args[0]=This args[1]=is args[0]=my args[0]=first args[0]=program While we pass the argument on the command line by using the second technique then the arguments are stored like this args[0]=This is my first program. To more clearly understand see the third technique: javac CommandLine This is "my first program" C:\Upload>java CommandLine This is "my first program" ---------------------------------------------------------This is my first program ---------------------------------------------------------- The third output clears that the arguments in the above output are stored like this: args[0]=This args[1]=is args[0]=my first program Summary: In this chapter you studied about the differences and the similarities between the java applets and application. and what is the roll of java application and the java applet in java programming. Java applications are flexible in linking with the java native code and security than applets. So the overall conclusion is that both java applications and java applets have the same priority but at their own places. If java application is more flexible at one place then it has some drawback at other place where its counterpart java applet provides the more flexibility The Life cycle of An AppletIntroduction In this Section you will learn about the lifecycle of an applet and different methods of an applet. Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed. Here are the lifecycle methods of an Applet: init(): This method is called to initialized an applet start(): This method is called after the initialization of the applet. stop(): This method can be called multiple times in the life cycle of an Applet. destroy(): This method is called only once in the life cycle of the applet when applet is destroyed. init () method: The life cycle of an applet is begin on that time when the applet is first loaded into the browser and called the init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init () method .After the initialization of the init() method user can interact with the Applet and mostly applet contains the init() method. Start () method: The start method of an applet is called after the initialization method init(). This method may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. In the start method user can interact within the applet. Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. There is only miner difference between the start() method and stop () method. For example the stop() method is called by the web browseron that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet. destroy() method: The destroy() method is called only one time in the life cycle of Applet like init() method. This method is called only on that time when the browser needs to Shut down. What is HTML File Now a days Java has become so stupendous that we can't even think ofWWW (World Wide Web) without it. As we all know that WWW is a collection of computing and information resources. These resources are connected together in a computer network known as the Internet. This collection which is known as Internet can be used for standard intercommunication and file transfer between computers. Initially Java appletsstarted off with a bang and continue to be the most widespread implementations of the language. However, the invention of World Wide Web by CERN in Switzerland caused a tremendous evolution in the world of Internet. He introduced a technology known as hypertext. This technology enables the users to click on highlighted links and automatically jump to that topic. Other than the technologies like HTTP (theHyperText Transport Protocol), and World Wide Web browsers such as Netscape Navigator, Microsoft Internet Explorer, and Sun HotJava, the most which is widely in use is HTML page in which the applet is embedded. The working of HTML text is as follows. 1. The information is passed by both the computers using the TCP/IP protocol. This means that the IP addresses will be assigned to both the computers. 2. Then using the HTTP protocol both computers will create connections to each other. This protocol processes send and request commands using the pipe created by TCP/IP between the two computers. HTTP will also enable the client to post information to the server. 3. Both computers must be visible to each other. The magic of World Wide Web begins once this connection is established. The users who are new to HTML have this misconception that the HTML files are actually programs that run within the browser. However to be more precise an HTML file is simply a text file containing a number of special codes known as tags. The browsers use these tags to display text, graphics, multimedia and applets on the screen. What Exactly is HTML? Now lets see what exactly is HTML(Hyper Text Markup Language). It is a type of data file which is transferred to the client machine. The HTML file gets translated and displayed on the screen if the client is using a Web browser like Netscape Navigator, Microsoft InternetExplorer etc. Let me give you a brief description of HTML. What is an HTML File? y y y y y HTML stands for Hyper Text Markup Language. An HTML file is a text file containing small markup tags. The markup tags tell the Web browser how to display the page. An HTML file must have an htm or html file extension. An HTML file can be created using a simple text editor. Go ahead and try it! If you are running Windows, start Notepad. If you are using Mac, start SimpleText. Start TextEdit in OSX and change the following preferences: Open the the "Format" menu and select "Plain text" instead of "Rich text". Then open the "Preferences" window under the "Text Edit" menu and select "Ignore rich text commands in HTML files". If you do not change the preferences above, your HTML code will probably not work. Type in the following text: <html> <head><title>Title <body> This is my </body> </html><html> <head><title>Title <body> This is my </body> </html> of page</title></head> first homepage. <b>This text is bold</b> of page</title></head> first homepage. <b>This text is bold</b> Save the file as "firstpage.htm". Start your Internet browser. Select "Open" (or "Open Page") in the File menu of your browser. A dialog box will appear. Select "Browse" (or "Choose File") and locate the HTML file you just created - "firstpage.htm" - select it and click "Open". Now you should see an address in thedialog box, for example "C:\MyDocuments\firstpage.htm". Click OK, and the browser will display the page. Lets have a look at print preview of the above example. Description of the above Example. We have started the HTML document by using the <html> tag and ended the same by using </html> tag. These two tags tell the browser about the starting and the ending of the document. Points to note: y y y y Although header information doesn't not get displayed in the browser window, we have given the header information by using <html> and </html> tags. Similarly we can give the title of the document by using the <title>, </title> tags which gets displayed in the browser's caption. The <body> tag is used to give a body of the document to be displayed in the browser. The text between the <b> and </b> tags is used to display the text in a bold font. Remember, use either the .htm or the .html extension while saving an HTML file. Well, it is preferable to use .html extension. Java and HTML: The Basics Before going any further lets start with the basics of HTML first. In this section we will come to know about all the tags which are required for the applet to be displayed within the browser. HTML provides a tag that enables the developer to "embed" the applet within the page. This tag is known as the APPLET tag. HTML Tags y y y HTML tags are used to mark-up HTML elements HTML tags are surrounded by the two characters < and > The surrounding characters are called angle brackets y y y y HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag The text between the start and end tags is the element content HTML tags are not case sensitive, <b> means the same as <B> HTML Elements Recall the HTML example from the previous previous section: <html> <head> <title>Title of page</title> </head> <body> This is my first homepage. <b>This text is bold</b> </body> </html> Now lets see what are HTML elements: <b>This text is bold</b> The HTML element starts with a start tag <b> and ends with </b> tag. The content of the HTML element is: This text is bold The <b> tag is used to define an HTML element that should be displayed as bold. Another HTML element is: <body> This is my first homepage. <b>This text is bold</b> </body> This HTML element starts with the start tag <body> and ends with the end tag </body>. Here the <body> tag defines the HTML element that contains the body of the HTML document. Setting Up the Title: The <HEAD> and the <TITLE> Tags We have already learned that how to use the <HEAD> and the <TITLE> Tags to display the information on the document. However, I would like to tell you that the browser starts processing the HTML document when it sees the <HTML> tag. Furthermore, we use the HEAD tag after the HTML tag which contains the information though the information doesn't appear directly on the page. However, any information which we insert in the TITLE tag gets displayed on the blue bar of theWeb browser. As shown below. <HTML> <HEAD> <TITLE>This is my first homepage!</TITLE> </HEAD> </HTML> The <BODY> Tag Now lets add a little bit of more information to our document. For this we will use BODY tag as you are already familiar with. As shown below. <HTML> <HEAD> <TITLE>This is my applet's first home!</TITLE> </HEAD> <BODY> </BODY> </HTML> Well the above HTML code will display a blank screen. To make the text more live we use number of HTML tags. The two most commonly used tags are the heading tags and paragraphtags which are described below. Headings As by the name headings always appear at the top of any any text or paragraph. There are six levels of headings in HTML. These headings are defined with the <h1> to <h6> tags. The <h1> defines the largest heading and <h6> defines the smallest heading. The tags are given below. <h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> <h4>This is a heading</h4> <h5>This is a heading</h5> <h6>This is a heading</h6> NOTE : HTML automatically adds an extra blank line before and after a heading. <html> <head> <title>HTML Heading Example</title> </head> <body> <h1>This <h2>This <h3>This <h4>This <h5>This <h6>This is is is is is is </body> </html> Output for the above code: Heading Heading Heading Heading Heading Heading 1</h1> 2</h2> 3</h3> 4</h4> 5</h5> 6</h6> Paragraphs One of the most common tags used to contain regular text in HTML is the paragraph tag. The <p> tag is used to insert a paragraph as shown below. <p>This is a paragraph</p> <p>This is another paragraph</p> <html> <head> <title>This is my applet's first home!</title> </head> <body> <p>You are learning html.</p> <p>This is the paragraph.</p> </body> </html> Output For The Above HTML Code: Line Breaks The <br> tag is used for line break. This tag is used to end a line i.e. to end a line without starting a new paragraph. The <br> tag forces a line break wherever you place it. They have no ending tag because they do not actually contain anything. The <br> tag is an empty tag. It has no closing tag. <p>My <br> new page<br> with line breaks</p> <html> <head> <title>Breaking a line</title> </head> <body> <p>Let us break<br/>the line.</p> </body> </html> Output For The Above HTML Code: Comments in HTML To explain your code, you can use comments which can help you when you edit the source code at a some time later. To insert a comment in the HTML source code, the comment tag is used. However a comment gets ignored by the browser. For instance. <!-- This is a comment --> Remember, to put an exclamation point after the opening bracket, but not before the closing bracket. The <APPLET> Tag in DetailAfter understanding a simple Java-enabledWeb page lets explore the APPLET tag now. The format of this tag is given below: <APPLET attributes> applet_parameters alternate_content </APPLET> <APPLET> Tag Attributes in detail. The three attributes of this tag are CODE/CODEBASE, WIDTH, and HEIGHT. One another point to note here that when we build <APPLET> tags the words such as APPLET and CODEBASE can be typed in either way as shown. The APPLET tag supports a number of standard attributes. The majority of these attributes are nearly identical to the attributes of the IMG tag (to be discussed later in this chapter). The three required attributes are CODE/CODEBASE, WIDTH, and HEIGHT. The following list describes each attribute and its meaning. Bold font indicates something you should type in exactly as shown except that letters don't need to be uppercase. To substitute a value for the word in italics, we use Italic font. Square brackets indicate that the contents of the brackets are optional. Lets tweak the example below. < APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = appletParameter1 VALUE = value >] [< PARAM NAME = appletParameter2 VALUE = value >] ... [alternateHTML] </APPLET> CODEBASE = codebaseURL This attribute is used to specify the base URL of the applet -- the directory or folder that contains the applet's code. The document's URL is used. if this attribute is not specified. CODE = appletFile This file is relative to the base URL of the applet and it cannot be absolute. This required attribute gives the name of the file that contains the applet's compiled Applet subclass. ALT = alternateText Any text that should be displayed is specified by this optional attribute if the browser understands the APPLET tag but can't run Java applets. NAME = appletInstanceName This optional attribute specifies a name for the applet instance. With the help of this attribute it is possible for applets on the same page to find (and communicate with) each other. WIDTH = pixels HEIGHT = pixels The initial width and height (in pixels) of the applet is given by these attributes to display area, not counting any windows or dialogs that the applet brings up. ALIGN = alignment This required attribute specifies the alignment of the applet with the same possible values (and have the same effects) as those for the IMG tag: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom. y y y y y y left-Aligns the applet at the left margin. The left and right values allow text to flow around the applet. (For spacing around the applet, see the VSPACE and HSPACE attributes.) right-Aligns the applet at the right margin. top-Aligns the applet with the topmost item on the current line in the HTML file. texttop-Aligns the applet with the top of the tallest text in the current line of the HTML file. middle-Aligns the applet with the middle of the baseline of the text in the current line of the HTML file. absmiddle-Aligns the middle of the applet with the middle of the largest item (text or otherwise) in the current line of the HTML file. y y y baseline-Aligns the bottom of the applet with the baseline of the current line of the HTML file. bottom-Equivalent to baseline. absbottom-Aligns the bottom of the applet with the lowest item (text or otherwise) in the current line of the HTML file. VSPACE = pixels HSPACE = pixels These optional attributes are used to specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). They're used the same way as the IMG tag's VSPACE and HSPACE attributes. < PARAM NAME = appletParameter1 VALUE = value > The only way to specify applet-specific parameters is to use the <PARAM> tags. Applets read user-specified values for parameters with the getParameter() method. alternateHTML If we use this <applet> tag in an HTML page to be viewed by the browser, probably the browser will ignore the <APPLET> and <PARAM> tags that doesn't understand the <APPLET> tag. Instead of interpreting any other HTML code between the <APPLET> and </APPLET> tags. Java-compatible browsers ignore this extra HTML code <APPLET> Tag Parameters: The <PARAM> TagThese are the parameters passed directly to a Java applet. Parameters are to applets what command-line arguments are toapplications. These parameters allow the user to customize the applet's operation. APPLET parameters stored in the PARAM tag actually have little directly to do with HTML. It is the responsibility of the applet to check the parameter values and respond accordingly. We can increase the applet's flexibility, making the applet work in multiple situations without recoding and recompiling it, by defining the parameters. The two steps of passing parameters to applets are: 1. First, add the PARAM tag (with values) to the HTML source file. 2. Second, add necessary code to the applet to retrieve these parameter values. Lets see how to Pass Parameters to the Applet <PARAM NAME=param_name VALUE=param_value> We use the above syntax to pass the parameters to the applet. In this syntax, param_name and param_value are the values passed to the Java applet. Retrieving Parameters Within the Applet These parameter values are retrieved by Java applets using the getParameter() method. This function is commonly called in the applet's init() method. The method syntax is the following: String getParameter(String name); Don't forget that the parameter names are case-sensitive when passing parameters to applets. Moreover all parameter values are converted to strings. HTML Document Creation We have already come to know about the Java Applets to be embedded within the HTML pages. There are several tags used in HTML however in this section we will provide an introduction to HTML for Java programmers. We have already learned the following tags. * <HTML> HTML tag * <HEAD> Header tag that can contain document information * <TITLE> Header title tag that contains the document title * <BODY> Body tag * <H1>-<H6> Body heading tags * <P> Body paragraph tag * <BR> Body line breaks * <APPLET> Java applet tag Additional Header Information As we know how to use the HEAD and the TITLE tags, there are two more additional tags which are commonly used to insert the information into the HTML file. The <META> Tag The header tag can also contains the meta tag. Each document can contain an unlimited number of META tags. This data is a miscellaneous information that may be of use to someone that views the HTML source at a later date. <META> has three attributes: NAME-Used to define what information is stored in the current META tag. If NAME is used, HTTP-EQUIV should not be. CONTENT-The CONTENT attribute defines the actual contents of the META tag. HTTP-EQUIV- This enables the HTML author to tie the contents of a META tag to an HTTP server's response header. NAME should not be used if HTTP-EQUIV is used, NAME should not be. Lets tweak the example: <HTML> <HEAD> <TITLE>Sample Meta Information</TITLE> <META NAME="Creation_Date" CONTENT="May 4, 2000"> <META NAME="Author" CONTENT="Jennifer"> </HEAD> </HTML> The <BASE> Tag To furnish a self-referencing URL for the document HTML provides a <BASE>tag. This enables the remaining URLs to contain relative location information within the document instead of continually "hard-wiring" themselves. This is useful if a document is being used again and again at several locations. The BASE tag has one attribute: HREF-The HREF attribute is used to store the URL of the document containing the BASE tag. Overall Document Formatting Several tags provided by HTML allow the document to provide a more visually appealing appearance by modifying the BODY Tag. It has several attributes. These attributes include the BGCOLOR, BACKGROUND, TEXT, LINK, VLINK, and ALINK attributes. * BGCOLOR-Sets the background color of the document. * BACKGROUND-Designates the URL of the background image to be used. * TEXT-Sets the color of regular text (overrides browser defaults). * LINK-Sets the color of hyperlinks (overrides browser defaults). * VLINK-Sets the color of visited links (overrides browser defaults). * ALINK-Sets the color of active links (overrides browser defaults). Complete Text Formatting Text Formatting is the ability to change the size, type, and color of fonts, modify the highlighting of characters to show emphasis, and add onscreen effects such as horizontal lines and background coloring. Text Tags The modification of various character styles to add effects to a document is done by the Text Tags. The following paragraphs shows the most popular of these styles, The <B>«</B> and <STRONG>«</STRONG> tags are used to boldface text. For these tags simply place the text to be made bold within these tags. Italicizing Text The <I>«</I> and <EM>«</EM> tags are used to italicize text. Setting the Base Font The BASEFONT tag forces the size of all text within the page. It has one attribute, SIZE. The syntax is <BASEFONT SIZE=25> Using Anchors to Create Hyperlinks The ability to create hyperlinks to other documents is accomplished by the Anchors. To embed these hyperlinks as part of the current document with the implementation hidden from the reader. HTML allows the creation of these hyperlinks through the use of the Anchor (<A>«</A>) tag. The <A>«</A> tag by itself does nothing. To create hyperlinks, the <A>«</A> tag must be used in conjunction with one of its attributes such as HREF or NAME. Linking to Another URL The HREF attribute is used to link to another URL from the current document. The <A> tag is called an anchor because it "anchors" text to a URL. Here is the syntax: <A HREF="URL">LocationNameInText</A> The actual location name displayed to the user is not an actual attribute. Instead, it is "anchored" to the HREF attribute. Linking within the Page The NAME attribute is used to jump to a location at the end of the document to point to a remote URL. Using the NAME attribute actually requires two steps: Using an anchor to set a link to the NAMED location. Setting the NAMED location through the use of the # character. The syntax is <A HREF="#named_location">named_location_text</A> . . . <A NAME="named_location">link_name_text</A> HTML and Images We can improve the document's visual appeal by adding images to an HTML document. The HTML IMAGE tag is used to accomplish this task. The basic syntax for using the IMAGE tag is the following: <IMG SRC="graphic_URL"> The following list gives more information on IMAGE tag attributes. 1. SRC-Used to set the URL of the image being loaded. 2. ALT-Contains text that will be displayed in text-only browsers (or browsers that have image-loading turned off). 3. ALIGN-Can be one of two possible values: TOP or MIDDLE. These values behave the same as the APPLET tag's ALIGN attribute Java Applet - Creating First Applet Example Introduction First of all we will know about the applet. An applet is a program written in javaprogramming language and embedded within HTML page. It run on the java enabled web browser such as Netscape navigator or Internet Explorer. In this example you will see, how to write an applet program. Java source of applet is then compiled into java class file and we specify the name of class in the applet tag of html page. The java enabled browser loads class file of applet and run in its sandbox. Here is the java code of program : import java.applet.*; import java.awt.*; public class FirstApplet extends Applet{ public void paint(Graphics g){ g.drawString("Welcome in Java Applet.",40,20); } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800"HEIGHT="5 00"></APPLET> </BODY> </HTML> Java - Drawing Shapes Example in java Java - Drawing Shapes Example in java Introduction Applet is a program to run on the browser and it is embedded on the web page. This program is not system level program but it is a network level program. The Applet class is a super class of any applet. Applet viewer is used to view or test the applet whether the applet is running properly or not. In this program we will see how to draw the different types of shapes like line, circle and rectangle. There are different types of methods for the Graphics class of the java.awt.*; package have been used to draw the appropriate shape. Explanation of the methods used in the program is given just ahead : Graphics.drawLine() : The drawLine() method has been used in the program to draw the line in the applet. Here is the syntax for the drawLine() method : drawLine(int X_from_coordinate, int Y_from_coordinate, int X_to_coordinate, int Y_to_coordinate); Graphics.drawString() : The drawSring() method draws the given string as the parameter. Here is the syntax of thedrawString() method : drawString(String string, int X_coordinate, int Y_coordinate); Graphics.drawOval() : The drawOval() method draws the circle. Here is the syntax of the drawOval() method : g.drawOval(int X_coordinate, int Y_coordinate, int Wdth, int height); Graphics.drawRect() : The drawRect() method draws the rectangle. Here is the syntax of thedrawRect() method : g.drawRect(int X_coordinate, int Y_coordinate, int Wdth, int height) Here is the java code of the program :. import java.applet.*; import java.awt.*; public class CircleLine extends Applet{ int x=300,y=100,r=50; public void paint(Graphics g){ g.drawLine(3,300,200,10); g.drawString("Line",100,100); g.drawOval(x-r,y-r,100,100); g.drawString("Circle",275,100); g.drawRect(400,50,200,100); g.drawString("Rectangel",450,100); } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <div align="center"> <APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET> </div> </BODY> </HTML> Introduction Applet is a program to run on the browser and it is embedded on the web page. This program is not system level program but it is a network level program. The Applet class is a super class of any applet. Applet viewer is used to view or test the applet whether the applet is running properly or not. In this program we will see how to draw the different types of shapes like line, circle and rectangle. There are different types of methods for the Graphics class of the java.awt.*; package have been used to draw the appropriate shape. Explanation of the methods used in the program is given just ahead : Graphics.drawLine() : The drawLine() method has been used in the program to draw the line in the applet. Here is the syntax for the drawLine() method : drawLine(int X_from_coordinate, int Y_from_coordinate, int X_to_coordinate, int Y_to_coordinate); Graphics.drawString() : The drawSring() method draws the given string as the parameter. Here is the syntax of thedrawString() method : drawString(String string, int X_coordinate, int Y_coordinate); Graphics.drawOval() : The drawOval() method draws the circle. Here is the syntax of the drawOval() method : g.drawOval(int X_coordinate, int Y_coordinate, int Wdth, int height); Graphics.drawRect() : The drawRect() method draws the rectangle. Here is the syntax of thedrawRect() method : g.drawRect(int X_coordinate, int Y_coordinate, int Wdth, int height) Here is the java code of the program :. import java.applet.*; import java.awt.*; public class CircleLine extends Applet{ int x=300,y=100,r=50; public void paint(Graphics g){ g.drawLine(3,300,200,10); g.drawString("Line",100,100); g.drawOval(x-r,y-r,100,100); g.drawString("Circle",275,100); g.drawRect(400,50,200,100); g.drawString("Rectangel",450,100); } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <div align="center"> <APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET> </div> </BODY> </HTML> Java - Drawing Shapes Example using color in java Introduction In this program we will show you how to draw the different types of colorful shapes. This example show the different types of colorful shapes like line, circle and the rectangle. It also displays the different - different colors such as red, magenta and yellow to be used in those shapes. In this program there are several types of methods have been used to fill or set the color of line, text, circle background and rectangle background. These are given just ahead : Graphics.setColor() : This is the setColor() method which is the Graphics class method imported by the java.awt.*;package. This method sets the color for the object by specified color. Here is the syntax of thesetColor() method : g.setColor(Color.color_name); Graphics.fillOval() : This is the fillOval() method used to fill the color inside the oval by specified color. Here is the syntax of the fillColor() method : g.fillColor(Color.color_name); Graphics.fillRect() : This is the fillRect() method used to fill the color inside the rectangle by specified color. Here is the syntax of the fillRect() method : g.fillRect(int X_coordinate, int Y_coordinate, int Wdth, int height) Here is the java code of the program :. import java.applet.*; import java.awt.*; public class ShapColor extends Applet{ int x=300,y=100,r=50; public void paint(Graphics g){ g.setColor(Color.red); //Drawing line color is red g.drawLine(3,300,200,10); g.setColor(Color.magenta); g.drawString("Line",100,100); g.drawOval(x-r,y-r,100,100); g.setColor(Color.yellow); //Fill the yellow color in circle g.fillOval( x-r,y-r, 100, 100 ); g.setColor(Color.magenta); g.drawString("Circle",275,100); g.drawRect(400,50,200,100); g.setColor(Color.yellow); //Fill the yellow color in rectangel g.fillRect( 400, 50, 200, 100 ); g.setColor(Color.magenta); g.drawString("Rectangel",450,100); } } Here is the HTML code of the program: <HTML> <HEAD> </HEAD> <BODY> <div align="center"> <APPLET ALIGN = "CENTER" CODE = "ShapColor.class" WIDTH = "800">HEIGHT = "500"></APPLET> </div> </BODY> </HTML> Java - Event Listeners Example in Java Applet Introduction The event listener is the feature of java that handles the several events for the several objects, Such as: MouseEvent, KeyEvent, TextEvent, InputEvent etc. Classes for helping in implementing event listeners are present in the java.awt.event.*; package. So, to use the events handling in your application import the java.awt.event.*;package. This example illustrates that how to handle several events fired on the several objects. In this example you will see that how to use the event listener and to perform appropriate tasks. In this example the EventListeners.java is our applet class which implements the ActionListener interface. Here four buttons and integer types variables have been used with specific values to perform the Addition, Subtraction, Multiplication and Division operations. All these operations are controlled by the events generated by these buttons. The Text Area named txtArea holds the result of the operation. There are two methods like init() and actionPerformed() have been used in this program for performing the whole operation. To handle the events generated by these buttons you add action listeners e.g. object_name.addActionListener(this);. When the action event occurs, that object's actionPerformed method is invoked. actionPerformed(ActionEvent e) Here is the java code of the program: import java.applet.*; import java.awt.event.*; import java.awt.*; public class EventListeners extends Applet implements ActionListener{ TextArea txtArea; String Add, Subtract,Multiply,Divide; int i = 10, j = 20, sum =0,Sub=0,Mul = 0,Div = 0; public void init(){ txtArea = new TextArea(10,20); txtArea.setEditable(false); add(txtArea,"center"); Button b = new Button("Add"); Button c = new Button("Subtract"); Button d = new Button("Multiply"); Button e = new Button("Divide"); b.addActionListener(this); c.addActionListener(this); d.addActionListener(this); e.addActionListener(this); add(b); add(c); add(d); add(e); } public void actionPerformed(ActionEvent e){ sum = i + j; txtArea.setText(""); txtArea.append("i = "+ i + "\t" + "j = " + j + "\n"); Button source = (Button)e.getSource(); if(source.getLabel() == "Add"){ txtArea.append("Sum : " + sum + "\n"); } if(i >j){ Sub = i - j; } else{ Sub = j - i; } if(source.getLabel() == "Subtract"){ txtArea.append("Sub : " + Sub + "\n"); } Mul = i*j; if(source.getLabel() == "Multiply"){ txtArea.append("Mul = " + Mul + "\n"); } if(i > j){ Div = i / j; } else{ Div = j / i; } if(source.getLabel() == "Divide"){ txtArea.append("Divide = " + Div); } } } Here is the HTML code of the program : <HTML> <BODY> <APPLET CODE ="EventListeners" WIDTH="800" HEIGHT="500"></APPLET> </BODY> </HTML> Applet - Passing Parameter in Java Applet Introduction Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. The paramtag(<parma name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of applet and passing parameter in applet, a example is given below. In this example, we will see what has to be done in the applet code to retrieve the value from parameters. Value of a parameter passed to an applet can be retrieved using getParameter()function. E.g. code: String strParameter = this.getParameter("Message"); Printing the value: Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html page. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will display the value passed as parameter. In our case applet should display "Welcome in Passing parameter in java applet example." message. Here is the code for the Java Program : import java.applet.*; import java.awt.*; public class appletParameter extends Applet { private String strDefault = "Hello! Java Applet."; public void paint(Graphics g) { String strParameter = this.getParameter("Message"); if (strParameter == null) strParameter = strDefault; g.drawString(strParameter, 50, 25); } } Here is the code for the html program : <HTML> <HEAD> <TITLE>Passing Parameter in Java Applet</TITLE> </HEAD> <BODY> This is the applet:<P> <APPLET code="appletParameter.class" width="800" height="100"> <PARAM name="message" value="Welcome in Passing parameter in java applet example."> </APPLET> </BODY> </HTML> There is the advantage that if need to change the output then you will have to change only the value of the param tag in html file not in java code. Compile the program : javac appletParameter.java Output after running the program : To run the program using appletviewer, go to command prompt and type appletviewer appletParameter.html Appletviewer will run the applet for you and and it should show output like Welcome in Passing parameter in java applet example. Alternatively you can also run this example from your favorite java enabled browser. Try the example online Download this example. Opening a URL from an Applet Introduction This is the example of opening a url in same window from an applet. This program shows that how a url is opened in same document or browser window. In this program you will see that many features have been used for opening url from an applet. This program is using two functions in which one is init() and another is actionPerformed(ActionListener ae).Function init() is self executed when the program is loaded on the browser. In the init() function a button labeled "Google" is created and it's action is performed using the statementb.addActionListener(this) which passes the object. And all the actions are performed in the another one function actionPerformed(ActionEvent ae) which gets the object ae of theActionEvent class. Object ae tells you about the source of the event through ae.getSource()which is stored in the Button type source variable after changing the type of the retrieved event-source object and source.getLabel() gives you the caption of the button. AppletContext has been used in this program. In fact AppletContext is the interface defines the methods, that allow an applet to interact with the context in which it runs (which is usually a Webbrowser or an applet viewer). And getAppletContext() is used to the reference for the AppletContext interface. To get the AppletContext of the applet getAppletContext() function can be used. We have used the function getAppletContext.showDocument(u,"_self") that loads the web page linked to the url. In the first case the applet page will be replaced. In the second case, _self is the target which can be : a. b. c. d. e. "_self" "_parent" "_top" "_blank" "string" - show in current frame - show in parent container - show in topmost frame - show in a new, top-level window - show in a frame with that string name. import java.applet.*; import java.awt.*; import java.net.*; import java.awt.event.*; public class tesURL extends Applet implements ActionListener{ public void init(){ String link_Text = "google"; Button b = new Button(link_Text); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent ae){ //get the button label Button source = (Button)ae.getSource(); // // String link = "http://www."+source.getLabel()+".com"; try { AppletContext a = getAppletContext(); URL u = new URL(link); a.showDocument(u,"_blank"); _blank to open page in new window a.showDocument(u,"_self"); } catch (MalformedURLException e){ System.out.println(e.getMessage()); } } } Java - Opening a url in new window from an applet Introduction In this example you will learn how to open a new window from an applet. You can use the code given in this program to open any url by replacing the value of url. In this example our applet will open newbrowser window and then show you theweb page. Opening a new window from applet is rather very simple task as all the necessary functions are already available. When you click the button "google" button on the applet, new browser window will open displaying the specified url, in our case url is http://www.google.com. This is accomplished by specifying the target as " _blank" while calling getAppletContext.showDocument(url, target)function. Here is the code of the program : import java.applet.*; import java.awt.*; import java.net.*; import java.awt.event.*; public class testURL_NewWindow extends Applet implements ActionListener{ public void init(){ String link_Text = "google"; Button b = new Button(link_Text); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent ae){ //get the button label Button source = (Button)ae.getSource(); String link = "http://www."+source.getLabel()+".com"; try { AppletContext a = getAppletContext(); URL url = new URL(link); a.showDocument(url,"_blank"); // a.showDocument(url,"_self"); // _self to open page in same window } catch (MalformedURLException e){ System.out.println(e.getMessage()); } } } Try online this example. Applet is not Working This section describes you some of the trouble shooting when your applet is not working in the browser Are you running Mac OS 9? Firstly check which browser are you using. If you are using Netscape 4.0(or less) with MacOS then try to run the applet applet on Internet Explorer or on differentOperating system like Linux. What version browser do you have? Check the version of your browser by clicking on the µHelp¶ menu and then select the µAbout¶. And make you using at least version 5.0 (Netscape / IE). Is your browser set to run Java? If above things are ok then may be your browser does not configure to run java. y If you are using Netscape, then click the menu ³Edit´ and the ³Preferences´. It shows a screen with different categories. Click on ³Advanced´ and make sure the ³Enabled Java´ box is checked. y If you are using Internet Explorer, click on Menu ³Tools´ and then select the ³Internet Options´ then click on the ³Security´ tab. Then click on the ³Custom Level´ Button, it shows you a security settings list. You have to scroll down this list until you find ³Java : Java Permissions´. Make sure about the java is not disabled and the security is not very high. y If you are using Safari, then in the Safari Menu select the ³Preferences¶, then click on theSecurity tab. Make sure that Enabled Java box is checked y In the latest versions of Opera and FireFox they do not include Java by default. You have to install it. Does your browser support java 1.3? Now Internet Explorer 6.0 on Windows XP is also comes without Java support or with the old Java support like Java 1.1. To fix this problem you have to install the browser plugin from the Sun's website. Java - Read file Applet Introduction In this program we will show you about the concept of the reading file from an applet. This program illustrates you how an applet can read the content from the given file. In this program we passes the file name as applet parameter which is then read by the applet program. If you specify the file name( which has to be read ) in the html file then the program will read the file otherwise applet will read the specified file for the String type variable named fileToRead. There are two functions have been used in the program. One is init() which is the first step of the life cycle for an applet in which you can initialize or set anything to start for the applet. The function init() initiates some variables, arrange objects in a applet like text area, and receive the file name in fileToRead variable from html file and calls the function readFile() that is the another function has been used. First of all readFile() function retrieve the path of the file to be read by the created object url from the URL class which is importing using the statement import java.net.*;package. The url object retrieves the file using getCodeBase() pattern which returns the parent of the html file the applet is embedded in, not the URL of the applet itself. And then the functionreadFile() creates a instance of the StringBuffer to store the file content. Finally program printsthe buffered string in the text area which will be seen in the applet on the web browser or applet viewer. Full running Read File Example code is given below: Here is the code of the program : import import import import java.applet.*; java.awt.*; java.io.*; java.net.*; public class readFileApplet extends Applet{ String fileToRead = "test1.txt"; StringBuffer strBuff; TextArea txtArea; Graphics g; public void init(){ txtArea = new TextArea(100, 100); txtArea.setEditable(false); add(txtArea, "center"); String prHtml = this.getParameter("fileToRead"); if (prHtml != null) fileToRead = new String(prHtml); readFile(); } public void readFile(){ String line; URL url = null; try{ url = new URL(getCodeBase(), fileToRead); } catch(MalformedURLException e){} try{ InputStream in = url.openStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(in)); strBuff = new StringBuffer(); while((line = bf.readLine()) != null){ strBuff.append(line + "\n"); } txtArea.append("File Name : " + fileToRead + "\n"); txtArea.append(strBuff.toString()); } catch(IOException e){ e.printStackTrace(); } } } Try online this example. Applet Write Files Example In this section, you will learn how to write to a file from an applet. This is very simple but the security manager don't provide the permission for writing a file from an applet. For this, you will have to maintain a Java security policy file that will allow the granted permission for writing a file from an applet. Without maintaining the Java security policy file, the security manager naturally installed during startup whenever an applet is started in the Java based web browser. By default the file writing permission is not allowed. All the permissions are allowed or disallowed in the policy file after that you write it or not. Description of program: The following program or code helps you in writing the content in a file from an applet. First of all this program creates a class (WriteFile) to extends the Applet class. After that, this program constructs aGUI layout that contains text field, text area and a command button. The text field has the name of file that have to be written and the text area provides a area for writing the user text that have to write in the given file. The common button performs your action ( for writing ). When you will run it (use theappletviewer -J-Djava.security.policy=po.policy WriteFileApplet.html), the GUI appears on the screen that takes the file name and text (content) on the specified locations. Without giving it, a message will appear on the screen in the message box (Please enter file name!). If the file name is entered without any text, even though it will display a message in the message box (Please enter your text!). You have entered both and click the "WriteToFile" command button, the file name is checked out. Whenever the file isn't exists, it will display a message in the message box (File not found!) and if the given file exists, the given text are written into the file and it will show a message in the message box (Text is written in vk.shtml) otherwise not and shows a message in the message box (Text isn't written in vk.shtml). You will try it. Here is the code of program (WriteFile.java): import import import import import import java.io.*; java.awt.*; java.awt.event.*; javax.swing.*; java.applet.Applet; java.net.*; public class WriteFile extends Applet{ Button write = new Button("WriteToFile"); Label label1 = new Label("Enter the file name:"); TextField text = new TextField(20); Label label2 = new Label("Write your text:"); TextArea area = new TextArea(10,20); public void init(){ add(label1); label1.setBackground(Color.lightGray); add(text); add(label2); label2.setBackground(Color.lightGray); add(area); add(write,BorderLayout.CENTER); write.addActionListener(new ActionListener (){ public void actionPerformed(ActionEvent e){ new WriteText(); } }); } public class WriteText { WriteText(){ try { String str = text.getText(); if(str.equals("")){ JOptionPane.showMessageDialog(null,"Please enter the file name!"); text.requestFocus(); } else{ File f = new File(str); if(f.exists()){ BufferedWriter out = new BufferedWriter(new FileWriter(f,true)); if(area.getText().equals("")){ JOptionPane.showMessageDialog(null,"Please enter your text!"); area.requestFocus(); } else{ out.write(area.getText()); if(f.canWrite()){ JOptionPane.showMessageDialog(null,"Text is written in "+str); text.setText(""); area.setText(""); text.requestFocus(); } else{ JOptionPane.showMessageDialog(null,"Text isn't written in "+str ); } out.close(); } } else{ JOptionPane.showMessageDialog(null,"File not found!"); text.setText(""); text.requestFocus(); } } } catch(Exception x){ x.printStackTrace(); } } } } Download this code. For running an applet you have to need an HTML file that uses the applet class to run this in the Java based web browser. Here is the HTML code (WriteFile.html): <HTML> <HEAD> <TITLE> Write file example </TITLE> <applet code="WriteFile.class",width="200",height="300"> </applet> </HEAD> </HTML> This is the policy file that allowed the permissions to the user for writing or reading the file from an applet. Here is the code of policy file (WriteFile.policy): grant { permission java.io.FilePermission "<<ALL FILES>>","write"; }; Output of program: Compile and run: C:\vinod\applet>javac WriteFile.java C:\vinod\applet>appletviewer -JDjava.security.policy=WriteFile.policy WriteFile.html appletviewer: This is the command that allows you for running the applets outside of a web browser. -Jjavaoption: The javaoption is a single argument string to the Java interpreter that runs the appletviewer. This argument hasn't spaces, if the argument contains the multiple words must be begin with '-J' prefix that is stripped and useful for adjusting the execution of compiler environment or memory usage. If file name is blank: If Text area is blank: Both are written: Message Box: Get the written file: vk.shtml Display image in the applet Introduction This program illustrates you to display image in an applet which has been done in this example. In this program you will see that how many methods, classes, packages and it's properties have been used to display the image in an applet. In this program only one functionpaint(Graphics g) has used. Functionpaint(Graphics g) is also a part of the life cycle of an applet in which anything you can draw in your applet to appear on the browser. In this function MediaTracker class of the java.awt.*; package, has been used. MediaTracker is a utility class that tracks the status of a number of media objects. And this type of object can include images and audio clips. In this program only the explanation about the adding images has been given. MediaTracker class is used after creating the instance for that and calling theaddImage() of the MediaTracker class which is used in this program as you can see. In this program method getImage() is used to return the image for the object ( img ) of the Image class taking two arguments, first is getCodeBase() and another is image name. Then the addImage()method of the MediaTracker has been used. Syntax of the addImage() function isMediaTracker.addImage(img, x, y, x1, y1). Arguments of addImage() function is explained below : img - image name type of Image. x - lower X - Coordinate type of int. y - lower Y - Coordinate type of int. x1 - upper X - Coordinate type of int. y1 - upper Y - Coordinate type of int. Here is the code of the program : import java.applet.*; import java.awt.*; public class appletImage extends Applet{ Image img; MediaTracker tr; public void paint(Graphics g) { tr = new MediaTracker(this); img = getImage(getCodeBase(), "freelinuxcds.gif"); tr.addImage(img,0); g.drawImage(img, 0, 0, this); } } Play Audio in Java Applet Introduction Java has the feature of the playing the sound file. This program will show you how to play a audio clip in your java appletviewer or on the browser. For this example we will be creating anapplet called PlaySoundApplet.java to play sound. There are two buttons to play the sound in Loop and to Stop the sound. The play() method of AudioClip object is used to play the sound while stop() method is used for stop the running audio clip suddenly. Here is the code of the program : import java.applet.*; import java.awt.*; import java.awt.event.*; public class PlaySoundApplet extends Applet implements ActionListener{ Button play,stop; AudioClip audioClip; public void init(){ play = new Button(" Play in Loop "); add(play); play.addActionListener(this); stop = new Button(" Stop "); add(stop); stop.addActionListener(this); audioClip = getAudioClip(getCodeBase(), "TestSnd.wav"); } public void actionPerformed(ActionEvent ae){ Button source = (Button)ae.getSource(); if (source.getLabel() == " Play in Loop "){ audioClip.play(); } else if(source.getLabel() == " Stop "){ audioClip.stop(); } } } AudioClip class: In this example we have a class AudioClip, which is an abstract class. So, it can't be instantiated directly. But there a method called getAudioClip() of Applet class which can be used to create the object of AudioClip. There are two versions of getAudioClip() function: 1. public AudioClip getAudioClip(URL url) 2. public AudioClip getAudioClip(URL url, String name) In this example we are using the second method: audioClip = getAudioClip(getCodeBase(), "TestSnd.wav"); AudioClip class provides the following methods: public abstract void play() - to play the sound only once public abstract void loop() - to play the sound in loop public abstract void stop() - to stop the playing sound Here is the HTML code : <HTML> <BODY> <APPLET CODE="PlaySoundApplet" WIDTH="200" HEIGHT="300"></APPLET> </BODY> </HTML> Try online this example Security Issues with the Applet Java applet is run inside a web browser. But an applet is restricted in some areas, until it has been deemed trustworthy by the end user. The security restriction is provided for protecting the user by malicious code, like copy important information from the hard disk or deleting the files. Generally, applets are loaded from the Internet and they are prevented from: the writing and reading the files on client side. Some security issues to applet are following : y Applets are loaded over the internet and they are prevented to make open network connection to any computer, except for the host, which provided the .class file. Because the html page come from the host or the host specified codebase parameter in the applet tag, with codebase taking precedence. y They are also prevented from starting other programs on the client. That means any applet, which you visited, cannot start any rogue process on you computer. In UNIX, applets cannot start any exec or fork processes. Applets are not allowed to invoke any program to list the contents of your file system that means it cant invoke System.exit() function to terminate you web browser. And they are not allowed to manipulate the threads outside the applets own thread group. y Applets are loaded over the net. A web browser uses only one class loader that¶s established at start up. Then the system class loader can not be overloaded, overridden, extended, replaced. Applet is not allowed to create the reference of their own class loader. y They cant load the libraries or define the native method calls. But if it can define native method calls then that would give the applet direct access to underlying computer. Java - Swing Applet Example in java Introduction In this section we will show you about using swing in an applet. In this example, you will see that how resources of swing are used in the applet. All objects exceptlbl, have been used from Applet class since lbl which inherits from the JLabel class of the javax.swing.*; package, this is swing label which shows the message in first timeThis is the Swing Applet Example. when the applet is loaded but again when you click on the Add button and if first text box is blank then the label lbl shows the message Invalid entry! in red color otherwise shows the message Output of the second Text Box : number_in_second_text_box. Here is the code of the program : import javax.swing.*; import java.applet.*; import java.awt.*; import java.awt.event.*; public class SApplet extends Applet implements ActionListener { TextField input,output; Label label1,label2; Button b1; JLabel lbl; int num, sum = 0; public void init(){ label1 = new Label("please enter number : "); add(label1); label1.setBackground(Color.yellow); label1.setForeground(Color.magenta); // input = new TextField(5); add(input); label2 = new Label("Sum : "); add(label2); label2.setBackground(Color.yellow); label2.setForeground(Color.magenta); output = new TextField(20); add(output); input.addActionListener( this ); b1 = new Button("Add"); add(b1); b1.addActionListener(this); lbl = new JLabel("This is the Swing Applet Example. add(lbl); setBackground(Color.yellow); "); // output.addActionListener( this ); } public void actionPerformed(ActionEvent ae){ try{ // num = Integer.parseInt(ae.getActionCommand()); num = Integer.parseInt(input.getText()); sum = sum+num; input.setText(""); output.setText(Integer.toString(sum)); lbl.setForeground(Color.blue); lbl.setText("Output of the second Text Box : " + output.getText()); } catch(NumberFormatException e){ lbl.setForeground(Color.red); lbl.setText("Invalid Entry!"); } } } Here is the HTML code : <HTML> <BODY> <applet code = "SApplet" width = "260"height = "200"></applet> </BODY> </HTML> Java - The Sample Banner Example in Java Introduction Here, we will learn about making the banner in java applet. Simply the banner is used to advertising for any institution, shops and any organizations. The advertising can be done by the different - different ways but the main aim is to popular our organization. For more popularity. But here, we will see what is a banner in the computer manner. As we know that the displaying detailed information in the graphics format on the page is known as banner. In other words, the banner is a collection of graphics and texts. With the help of banner we easily make to understand about the things. In this program we will see how to display the banner in applet. This example has been used to display the simple text rotation in a rectangular area of the appropriate applet to understand that what is the banner and how to use that. There are four types of method have been used in this program these are explained below one by one : init() : This is the init() method which is the first method of the life cycle of an applet has been used to set the Background and Foreground colors of the banner. start() : This is the start() method which is the second method of the life cycle of an applet has been used to create and start a thread. run() : This is the run() method which has been used to set the time interval for the created thread. That means the rotation of text to be rotate on how much time. paint() : And finally this is the paint() method which has been used to draw the rectangle, set it's color and display the moving text in the appropriate rectangle. Here is the Java code: import java.awt.*; import java.applet.*; public class SampleBanner extends Applet implements Runnable{ String str = "This is a simple Banner developed by Roseindia.net. "; Thread t ; boolean b; public void init() { setBackground(Color.gray); setForeground(Color.yellow); } public void start() { t = new Thread(this); b = false; t.start(); } public void run () { char ch; for( ; ; ) { try { repaint(); Thread.sleep(250); ch = str.charAt(0); str = str.substring(1, str.length()); str = str + ch; } catch(InterruptedException e) {} } } public void paint(Graphics g) { g.drawRect(1,1,300,150); g.setColor(Color.yellow); g.fillRect(1,1,300,150); g.setColor(Color.red); g.drawString(str, 1, 150); } } Here is the HTML code: <HTML> <BODY> <APPLET CODE = "SampleBanner" WIDTH = "500" HEIGHT = "300"></APPLET> </BODY> </HTML> Java - Clock Applet in Java Introduction Here is a sample of running clock provided by the java applet to illustrate how to use the clock in an applet. This program shows the current time. This type of program is used to display the time on browser where your application is running on. In this example we will see display the time in an applet in the time format like: hours, minutes and then seconds (hh:mm:ss). Here, the ClockApplet is a class name extends from the Applet class and implements to theRunnable interface. There are two threads used in this program. There are three methods have been used in this program to display the current time these are explained below : start() This is the start() method used in this program. This method creates a new instance t of the Thread class and starts it. run() This is the run() method which uses the Runnable interface. This method creates another Thread instance t1 and starts it. In this method the repaint() method has also been used to paint the applet viewer with it's objects again and again during the 1 second(1000 millisecond). pain(Graphics g) This is the paint() method which prints all the things in applet viewer or a browser. In this program sleep() method of the thread has been used to set the time interval of 1 minute andrepaint() method has been used to call the pain() method. Here is the code of the program : import java.applet.*; import java.awt.*; import java.util.*; public class ClockApplet extends Applet implements Runnable{ Thread t,t1; public void start(){ t = new Thread(this); t.start(); } public void run(){ t1 = Thread.currentThread(); while(t1 == t){ repaint(); try{ t1.sleep(1000); }catch(InterruptedException e){} } } public void paint(Graphics g){ Calendar cal = new GregorianCalendar(); String hour = String.valueOf(cal.get(Calendar.HOUR)); String minute = String.valueOf(cal.get(Calendar.MINUTE)); String second = String.valueOf(cal.get(Calendar.SECOND)); g.drawString(hour + ":" + minute + ":" + second, 20, 30); } } Here is the HTML code : <HTML> <BODY> <div align = "center"> <APPLET CODE = "ClockApplet" WIDTH = "500" HEIGHT = "400"></APPLET> </div> </BODY> </HTML> Java - Opening a url in new window from an applet This is the example of opening a url from an applet. This program shows that how a url is opened in a new document or browser. When you click the button "google", new browser window will open displaying the specified url, in our case url ishttp://www.google.com. This is accomplished by specifying the target as " _blank" while calling getAppletContext.showDocument(url, target) function. Here is the code of the program : import java.applet.*; import java.awt.*; import java.net.*; import java.awt.event.*; public class testURL_NewWindow extends Applet implements ActionListener{ public void init(){ String link_Text = "google"; Button b = new Button(link_Text); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent ae){ //get the button label Button source = (Button)ae.getSource(); String link = "http://www."+source.getLabel()+".com"; try { AppletContext a = getAppletContext(); URL url = new URL(link); a.showDocument(url,"_blank"); // a.showDocument(url,"_self"); // _self to open page in same window } catch (MalformedURLException e){ System.out.println(e.getMessage()); } } } Java - Opening a URL from an Applet This is the example of opening a url in same window from an applet. This program shows that how a url is opened in same document or browser window. In this program you will see that many features have been used for opening url from an applet. This program is using two functions in which one is init() and another is actionPerformed(ActionListener ae). Function init() is self executed when the program is loaded on the browser. In the init() function a button labeled "Google" is created and it's action is performed using the statement b.addActionListener(this) which passes the object. And all the actions are performed in the another one function actionPerformed(ActionEvent ae) which gets the object ae of the ActionEvent class. Object ae tells you about the source of the event through ae.getSource() which is stored in the Button type source variable after changing the type of the retrieved event-source object and source.getLabel() gives you the caption of the button. AppletContext has been used in this program. In fact AppletContext is the interface defines the methods, that allow an applet to interact with the context in which it runs (which is usually a Web browser or an applet viewer). And getAppletContext() is used to the reference for the AppletContext interface. To get the AppletContext of the applet getAppletContext() function can be used. We have used the function getAppletContext.showDocument(u,"_self") that loads the web page linked to the url. In the first case the applet page will be replaced. In the second case, _self is the target which can be : a. b. c. d. e. "_self" "_parent" "_top" "_blank" "string" import import import import - show in current frame - show in parent container - show in topmost frame - show in a new, top-level window - show in a frame with that string name. java.applet.*; java.awt.*; java.net.*; java.awt.event.*; public class tesURL extends Applet implements ActionListener{ public void init(){ String link_Text = "google"; Button b = new Button(link_Text); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent ae){ //get the button label Button source = (Button)ae.getSource(); // // } String link = "http://www."+source.getLabel()+".com"; try { AppletContext a = getAppletContext(); URL u = new URL(link); a.showDocument(u,"_blank"); _blank to open page in new window a.showDocument(u,"_self"); } catch (MalformedURLException e){ System.out.println(e.getMessage()); } } ...
View Full Document

Ask a homework question - tutors are online