Java Applet - Example

Example

The following example is made simple enough to illustrate the essential use of Java applets through its java.applet package. It also uses classes from the Java Abstract Window Toolkit (AWT) for producing actual output (in this case, the "Hello, world!" message).

import java.applet.Applet; import java.awt.*; // Applet code for the "Hello, world!" example. // This should be saved in a file named as "HelloWorld.java". public class HelloWorld extends Applet { // This method is mandatory, but can be empty (i.e., have no actual code). public void init { } // This method is mandatory, but can be empty.(i.e.,have no actual code). public void stop { } // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.drawString("Hello, world!", 20,10); // Draws a circle on the screen (x=40, y=30). g.drawArc(40,30,20,20,0,360); } }

Additional simple applets are available at Wikiversity.

For compiling, this code is saved on a plain-ASCII file with the same name as the class and .java extension, i.e. HelloWorld.java. The resulting HelloWorld.class applet should be placed on the web server and is invoked within an HTML page by using an or an tag. For example:

HelloWorld_example.html

A Java applet example

Here it is: This is where HelloWorld.class runs.

Displaying the HelloWorld_example.html page from a Web server, the result should look as this:

A Java applet example
Here it is: Hello, world!

To minimize download time, applets are usually delivered in a form of compressed zip archive (having jar extension). If all needed classes (only one in our case) are placed in compressed archive example.jar, the embedding code would look different:

Here it is: This is where HelloWorld.class runs.

Applet inclusion is described in detail in Sun's official page about the APPLET tag.

Read more about this topic:  Java Applet

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)