Return to the main page Home
Learn by reading articles about Java Library
Download free Java software here Applets
Play quality Java games online Arcade
Visit our links and play the Treasure Hunt Plaza
Sample site only. Please visit http://geocities.datacellar.net/davidchan for a complete list of sites created by David Chan.

Creating An Applet


Java™ applets are programs that are downloaded over the World Wide Web and run in your Web browser. Applets need a Java-capable browser in order to run. As applets are downloaded onto the user's system, Java applets have special rules on how they should behave. Because of this Java applets are more complex to create.

Java source files are created in a plain text editor, or an editor that saves plain ASCII files without character formatting. Some examples include Notepad or DOS edit.

Open your text editor and type in this program as shown:


import java.awt.Graphics;

public class Hello1 extends java.applet.Applet 
{
      public void paint(Graphics g) 
      {
            g.drawString("Hello, world", 5, 25);
      }
}

The import line at the top of the file allows the applet to access the JDK classes for creating applets and for drawing applets on the screen. The paint() method is used to show an applet's content on the screen.

Once you finish typing, save the file as "Hello1.java". Java files are usually saved with the same name as the class name with the extension ".java". To compile your program, you need a Java compiler. The compiler in Sun's JDK is called javac. Make sure javac is in your execution path then type the following:

javac Hello1.java

If you get a error when you compile, correct any typing mistakes you made before compiling again. You end up with a Java bytecode file called "Hello1.class" in the same directory as your source file.

To include the applet in a Web page, you need to refer to it in the HTML code for a Web page. Following is an example of a simple HTML file that refers to the applet:

<HTML>
<HEAD>
<TITLE>Hello Everybody!</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Hello1.class"
WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

The CODE attribute indicates the class name of your applet. WIDTH and HEIGHT refer to the size of your applet in pixels. Save the HTML file with a descriptive name such as "Hello1.html" then open it with a Java-capable browser or the appletviewer. To run the appletviewer type:

appletviewer Hello1.html

Don't forget to indicate the path to the HTML file. eg if you file is in the directory HTML you should type:

appletviewer HTML/Hello1.html

If your program was type and compiled correctly, the string "Hello, world" should be printed on your screen.

Next article


Return to the top of the page
Top of page


| Home | Library | Applets | Arcade | Plaza |

Please send any feedback to David Chan

1