16.2 A First Applet

Example 16-1 shows what is probably the simplest possible applet you can write in Java. Figure 16-1 shows the output it produces. This example introduces the paint( ) method, which is invoked by the applet viewer (or web browser) when the applet needs to be drawn. This method should perform graphical output such as drawing text or lines or displaying images for your applet. The argument to paint( ) is a java.awt.Graphics object that you use to do the drawing.

Figure 16-1. A simple applet
figs/jex3_1601.gif
Example 16-1. FirstApplet.java
package je3.applet; import java.applet.*;   // Don't forget this import statement! import java.awt.*;      // Or this one for the graphics! /** This applet just says "Hello World" */ public class FirstApplet extends Applet {     // This method displays the applet.     public void paint(Graphics g) {         g.drawString("Hello World", 25, 50);     } }

To display an applet, you need an HTML file that references it. Here is an HTML fragment that can be used with this first applet:

<applet code="je3.applet.FirstApplet.class"         codebase="../../"         width=150 height=100> </applet>

With an HTML file that references the applet, you can now view the applet with an applet viewer or web browser. Note that the WIDTH and HEIGHT attributes of this HTML tag are required. For most applet examples in this book, I show only the Java code, not the corresponding HTML file that goes with it. Typically, that HTML file contains a tag as simple as the one shown here.



Java Examples in a Nutshell
Java Examples in a Nutshell, 3rd Edition
ISBN: 0596006209
EAN: 2147483647
Year: 2003
Pages: 285

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