|
Creating An AppletJava 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> 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. | |||||||||||
|