Вы находитесь на странице: 1из 16

clA Java applet is an applet delivered in the form of Java bytecode.

Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand alone tool to test applets. Java applets were introduced in the first version of the Java language in 1995. Java applets are usually written in the Java programming language but they can also be written in other languages that compile to Java bytecode such as Jython. Applets are used to provide interactive features to web applications that cannot be provided by HTML. Since Java's bytecode is platform independent, Java applets can be executed by browsers for many platforms, including Windows, Unix, Mac OS and Linux. There are open source tools like applet2app which can be used to convert an applet to a stand alone Java application/windows executable. This has the advantage of running a Java applet in offline mode without the need for internet browser software. A Java Servlet is sometimes informally compared to be "like" a server-side applet, but it is different in its language, functions, and in each of the characteristics described here about applets. Technical information Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applet's user interface. The applet can be displayed on the web page by making use of the deprecated applet HTML element or the recommended object element. This specifies the applet's source and the applet's location statistics. A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (Applet is a descendant of Panel which is a descendant of Container). Advantages of applets A Java applet can have any or all of the following advantages: * it is simple to make it work on Windows, Mac OS and Linux, i.e. to make it cross platform * the same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the JRE the client will be forced wait during the large download. * it runs in a sandbox, so the user does not need to trust the code, so it can work without security approval * it is supported by most web browsers * it will cache in most web browsers, so will be quick to load when returning to a web page * it can have full access to the machine it is running on if the user agrees * it can improve with use: after a first applet is run, the JVM is already running and starts quickly, benefiting regular users of Java * it can run at a comparable (but generally slower) speed to other compiled languages such as C++ * it can be a real time application * it can move the work from the server to the client, making a web solution more scalable with the number of users/clients Disadvantages of applets A Java applet is open to any of the following disadvantages:

* it requires the Java plug-in, which isn't available by default on all web browsers * it can't start up until the Java Virtual Machine is running, and this may have significant startup time the first time it is used * if it is uncached, it must be downloaded (usually over the internet), and this takes time * it is considered more difficult to build and design a good user interface with applets than with HTML-based technologies * if untrusted, it has severely limited access to the user's system - in particular having no direct access to the client's disc or clipboard * some organizations only allow software installed by the administrators. As a result, many users cannot view applets by default. * applets may require a specific JRE. Compatibility issues Sun has made a considerable effort to ensure compatibility is maintained between Java versions as they evolve. For example, Microsoft's Internet Explorer, the most popular web browser since the late 1990s, used to ship with Microsoft's own JVM as the default. The MSJVM had some extra non-Java features added which, if used, would prevent MSJVM applets from running on Sun's Java (but not the other way round). Sun sued for breach of trademark, as the point of Java was that there should be no proprietary extensions and that code should work everywhere. Development of MSJVM was frozen by a legal settlement, leaving many users with an extremely outdated Java virtual machine. Later, in October 2001, MS stopped including Java with Windows, and for some years it has been left to the computer manufacturers to ship Java independently of the OS. Most new machines now ship with official Sun Java. Some browsers (notably Firefox) do not do a good job of handling height=100% on applets which makes it difficult to make an applet fill most of the browser window (Javascript can, with difficulty, be used for this). Having the applet create its own main window is not a good solution either, as this leads to a large chance of the applet getting terminated unintentionally and leaves the browser window as a largely useless extra window. Alternatives Alternative technologies exist (for example, DHTML and Flash) that satisfy some of the scope of what is possible with an applet. Another alternative to applets for client side Java is Java Web Start, which runs outside the browser. In addition to the features available to applets, a simple permissions box can give Java Web Start programs read and/or write access to specified files stored on the client, and to the client's clipboard.
Above article originally from wikipedia.org. Above article is available under t

ass Prime_number { public static void main(String[] args) { int num = 11; int i; for (i=2; i < num ;i++ ){ int n = num%i; if (n==0){ System.out.println("not Prime!"); break; } } if(i == num){ System.out.println("Prime number!");

Applet is java program that can be embedded into HTML pages. Java applets runs 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:

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 without security 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:


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

Introduction 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 browser on 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. Introduction First of all we will know about the applet. An applet is a program written in java programming 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="500"></APPLET> </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 the drawString() 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 the drawRect() 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 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 the setColor() 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> 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> 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 param tag(<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. 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 new browser window and then show you the web 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 import import import java.applet.*; java.awt.*; java.net.*; 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. 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 different Operating 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.

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. 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. If you are using Safari, then in the Safari Menu select the Preferences, then click on the Security tab. Make sure that Enabled Java box is checked 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. 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 function readFile() creates a instance of the StringBuffer to store the file content. Finally program prints the 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(); }

} }

Introduction 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 function paint(Graphics g) has used. Function paint(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 the addImage() 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 is MediaTracker.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); } }

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 applet viewer or on the browser. For this example we will be creating an applet 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>

Вам также может понравиться