A Simple Java Applet


This section describes how to create, compile, and execute a Java applet that you can run in a web browser.

Create the HTML Source File

Use a text editor to create a file named Hello.html with the text

 <applet code="HelloApplet" width=300 height=200> </applet>

You could also embed this HTML tag in an existing web page.

Create and Compile the Java Source File

Now create a file named HelloApplet.java with the following contents:

 import java.applet.Applet; import java.awt.Graphics; public class HelloApplet extends Applet{   public void paint (Graphics g) {     g.drawString ("Hello", 100, 100) ;   } }

Consider each of the lines in this program. The first and second lines import the Applet class from the java.applet package and the Graphics class from the java.awt package. This allows you to use partially qualified names for these two classes.

The third line declares HelloApplet as a subclass of Applet. HelloApplet inherits all of the basic applet functionality from its superclass.

The fourth line overrides the paint() method. It receives a Graphics object as its argument. That object provides methods to draw on the screen.

The fifth line invokes the drawString() method of the Graphics object. The first argument to this method is a string to be output. The second and third arguments are the x and y positions at which the string should be located. The upper-left corner of the applet display area is position 0, 0. Values along the x axis increase toward the right. Values along the y axis increase toward the bottom. The total drawing area of the applet was configured in the Hello.html file.

Before you can run your applet, you must compile it using javac:

 javac HelloApplet.java

Invoke the Applet Viewer

The applet viewer is one of the utilities that is included in the JDK. It allows you to execute an applet. Invoke this tool by entering the following on the command line:

 appletviewer Hello.html

The applet appears as shown in Figure 25–1.

image from book
Figure 25–1: A simple Java applet

It is also possible to run the appletviewer directly on a .java file (without an .html file) if you include the <applet> tags in a Java comment near the beginning of the file. However, you still need to compile your .java file with javac before running.

A more common way to view applets is in a web browser, by opening your .html file (to do this, look in the File menu for the option Open File). If it includes a JVM that is up to date, the browser will display the applet along with any HTML content.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net